· 6 years ago · Mar 10, 2019, 11:26 AM
1// Create a template of the key that we are going to generate.
2AESSecretKey secretKeyTemplate = new AESSecretKey();
3// Set the token value true. This saves the key in the token.
4secretKeyTemplate.getToken().setBooleanValue(Boolean.TRUE);
5// Makes key to be used for encrypting operations.
6secretKeyTemplate.getEncrypt().setBooleanValue(Boolean.TRUE);
7// Makes key to be used for decrypting operations.
8secretKeyTemplate.getDecrypt().setBooleanValue(Boolean.TRUE);
9// Make key private. When a key is private only authorized user can access the key.
10secretKeyTemplate.getPrivate().setBooleanValue(Voolean.TRUE);
11// Makes the key sensitive.
12secretKeyTemplate.getSensitive().setBooleanValue(Voolean.TRUE);
13// Makes the key not extractable. So key can't be retrieved outside the HSM.
14secretKeyTemplate.getExtractable().setBooleanValue(Voolean.FALSE);
15// Set a label to the key. Label can be used to retrieve the key.
16secretKeyTemplate.getLabel().setCharArrayValue("SampleAESKey".tocharArray());
17// Set the length of the key.
18secretKeyTemplate.getValueLen().setLongValue(32L);
19// Key template configuration is complete.
20
21// Selects the key generation mechanism.
22Mechanism keyGenMechanism = Mechanism.get(PKCS11Constants.CKM_AES_KEY_GEN);
23// Generates the key using the initiated session.
24AESSecretKey secretKey = (AESSecretKey) session.generateKey(keyMechanism, secretKeyTemplate);