I have generated a RSA public-private keypair in HSM using PKCS11Interop generate key API. I want to export the keypair. I used Findobject API to get the keys, the API returs an ObjectHandle , while reading attributes using GetAttributeValue API , I am not able to read the key's value. And when I set the key's attribute to CKA_EXTRACTABLE to true, I am not able to generate the key altogether.
Also I need to import externally provided keypair in HSM.
Any help is highly appreciated.
RSA private key can be exported with correct attribute settings (of course this scenario has to be supported by the unmanaged PKCS#11 library provided by HSM vendor), but you need to read multiple attributes (see chapter 12.1.3 of PKCS#11 v2.20 specification) to extract its parts and then create ASN.1 structure of the key on your own.
Particular type of ASN.1 structure you need depends on the key type you are using (in your case it's RSA) and on the capabilities of the target system that will use the keys i.e. encryption applications usually use different formats than e-mail agents etc. I believe you can start with
RSAPrivateKey
structure defined in PKCS#1.I think you are using Safenet HSM because Thales HSM does not have such functionalities like GetAttributeValue, ObjectHandle etc..
CKA_EXTRACTABLE means that you can extract your key under another key and this does not mean that you can read key data. It should be totally unsecure if you can get key data with just using key handle.
Reading key data with using ObjectHandle is not possible even in Functionality Module(FM). FM is proprietary software that only run in Safenet HSM itself, it is embedded sofware that run HSM hardware. You can use ObjectHandle to call specific HSM functions like encrypt, decrypt in FM. Extracting a key is only possible under another key.
You could import your keys with using Safenet HSM function calls.
What you are trying to do is considered
insecure
in the HSM world. It defeats the purpose of having an HSM.But, can it be done? Yes. Provided the HSM vendor should support it.
The HSM vendor decides if the keys generated on the HSM can be extractable or if any Key that was generated by any software (outside the HSM) can be imported into the hardware. PKCS#11 is just an interface through which you interact with the HSM. If the HSM doesn't support an operation, it throws an exception which is eventually thrown by the PKCS11 api.
This is what is happening in your case for both the extraction and importing operations. The HSM on which you are trying to do these operations may not support it. So you need to check with the HSM vendor how you can perform these operations on their product.
P.S: Thales nShield should/may have a configuration file through which you can run the HSM in insecure mode.
Note: Extracting a
Key/Key Pair
generated on the HSM (or) importing any Key/Key Pair that was generated outside the HSM are not considered as insecure operations in the real world.