aws-samples / aws-cloudhsm-jce-examples

Sample applications demonstrating how to use the CloudHSM JCE
MIT No Attribution
39 stars 57 forks source link

Problem with AES Wrap/Unwrap #82

Closed narasimhaks closed 11 months ago

narasimhaks commented 11 months ago

Hi,

I am trying to import an AES key into the HSM using an AES wrapping key generated in the HSM. When i try to call the wrap method i get the following error. Java Security InvalidKeyException: Non CloudHsm key is not supported for this cipher operation. Is wwrapping of an externally generated key (Non Cavium/CloudHSM key) not supported? I tried this on both SDK3 and SDK5 and get similar error. Please find my code snippet attached below.

Cipher cipher = Cipher.getInstance("AESWrap/ECB/NoPadding", CloudHsmProvider.PROVIDER_NAME);
KeyStore keyStore = KeyStore.getInstance(CloudHsmProvider.PROVIDER_NAME);
keyStore.load(null, null);
SecretKey wrapKey = (SecretKey) keyStore.getKey("wrappingkey", null);
cipher.init(Cipher.WRAP_MODE, wrapKey);
SecretKey originalKey = new SecretKeySpec(value, 0, value.length, "AES");
byte[] wrappedAESKey = cipher.wrap(originalKey); //Thows exception here
cipher.init(Cipher.UNWRAP_MODE, wrapKey);
Key key = cipher.unwrap(wrappedAESKey, "AES", Cipher.SECRET_KEY);
return key;

Appreciate any help in this regard.

Thanks Nara

rday commented 11 months ago

Hi @narasimhaks !

You're getting the exception on .wrap because originalKey doesn't exist in the HSM, it was just created on the previous line. Instead of using SecretKeySpec, you can generate a key in the HSM, then .wrap() that key to get the byte[] wrappedAESKey you are looking for.

If you have a wrapped key outside the HSM, that you want to import, you first need to get the Wrapping Key imported into the HSM. We have an example demonstrating how to use RSA to do this: https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/sdk5/src/main/java/com/amazonaws/cloudhsm/examples/RSAImportKey.java. You can also work with your TAM to find the best method for you situation.

narasimhaks commented 11 months ago

Hi @rday

I tried that approach you mentioned but the key is being imported into the HSM with a unique label. How can i set the KeyAttributesMap to have a custom label, make it persistent and extractable? When i tried to set it as below, i got a error.

KeyAttributesMap keySpec = new KeyAttributesMapBuilder().put(KeyAttribute.VALUE, importedKey.getEncoded()).build();
keySpec.put(KeyAttribute.LABEL, label);
keySpec.put(KeyAttribute.TOKEN, true);
keySpec.put(KeyAttribute.EXTRACTABLE, true);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("AES", CloudHsmProvider.PROVIDER_NAME);
keyFactory.generateSecret(keySpec);