Unwrapping RSA encrypted AES key using Safenet HSM and Java leaks the unwrapped key

Viewed 1946

I am using a Safenet HSM (Hardware Security Module) to store my cryptographic keys, and I am trying to unwrap a secret key (AES/DES) encrypted with RSA using Java APIs and SunPKCS11. I would like to do this securely, so that unwrapped AES/DES key cannot be extracted from the HSM (like the RSA private key value is invisible). However, after unwrapping the value of the unwrapped key is visible in the key object outside the HSM.

Here is my code:

Key privateKey = keyStore.getKey("MyKeyId", keyStorePassword);

Cipher cipher = Cipher.getInstance("RSA", "SunPKCS11-Safenet");
cipher.init(Cipher.UNWRAP_MODE, privateKey);
Key unwrappedKey = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
// At this point the unwrapped key is visible in the unwrappedKey object!

How I can tell the code not to reveal the unwrapped key? Do I have to add something in the PKCS11 config file? I've tried adding the options below into the config file, but it doesn't seem to help:

attributes(*,CKO_SECRET_KEY,*) = {
  CKA_SENSITIVE=true
}

I am not sure if revealing keys during unwrapping is expected from the API. If so, how I can import such keys securely into the HSM so that they cannot be extracted from it?

I've tried asking the Safenet support team, but they could not answer why this is happening. So, after lots of trying and searching the Internet, I have asked this question here.

1 Answers

If you unwrap the key... you get back the key. ie, unwrapping a key exposes the key. If you are asking the HSM to unwrap the key, it is doing what you told it to do.

Maybe you want to import the key instead, if the HSM supports this operation. The assumption on key import is that the HSM understands the format in which the key has been wrapped for security/protection/transport.

It will then do the unwrap for you, and save the unwrapped key in its database. Maybe it then hands you back the key as a handle, or as a differently wrapped key (ie, wrapped using its internal master key).

Moving a key between comparable HSMs is export/import or backup/restore, depending on the device and the devices' understanding of those verbs.

Moving a key between different vendor's HSMs or different cryptosystems, without exposing the secrets is an interesting exercise.

Related