'Unwrapping a private key wrapped with CKM_AES_KEY_WRAP mechanism

I am currently working on what we call “centralized enrolment” that is:

  1. Issue a keypair either RSA or EC on a HSM;
  2. Issue a symmetric session key on the same HSM;
  3. Wrap the private key with the session key using various mechanisms such as CKM_AES_CBC_PAD, CKM_AES_KEY_WRAP_PAD and CKM_AES_KEY_WRAP;
  4. Wrap the session key with an external RSA master key which is provided to the HSM;
  5. Return both protected keys.

When verifying the results, I succeed in unwrapping the session key (with the private key I own) but I am facing some difficulties in unwrapping the private key, when the mechanism is CKM_AES_KEY_WRAP. Everything works well with he other two.
As the session key is used only once, we let the HSM decide which IV to use (in the case of CKM_AES_CBC_PAD, it will be a 16 byte array of zeros).

What works well is:

case CKM_AES_KEY_WRAP_PAD -> {
  Cipher wrapper = Cipher.getInstance("AESWrapPad", "BC");
  wrapper.init(Cipher.UNWRAP_MODE, this.clearSecretKey);
  clearPrivateKey = (PrivateKey) wrapper.unwrap(privateKeyToRecover, algorithm, Cipher.PRIVATE_KEY);
}

and

case CKM_AES_CBC_PAD -> {
  byte[] ivb = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0};
  Cipher wrapper = Cipher.getInstance("AES/CBC/Pkcs7Padding", "BC");
  wrapper.init(Cipher.UNWRAP_MODE, this.clearSecretKey, new IvParameterSpec(ivb));
  clearPrivateKey = (PrivateKey) wrapper.unwrap(privateKeyToRecover, algorithm, Cipher.PRIVATE_KEY);
}

What fails is:

case CKM_AES_KEY_WRAP -> {
  Cipher wrapper = Cipher.getInstance("AESWrap", "BC");
  wrapper.init(Cipher.UNWRAP_MODE, this.clearSecretKey);
  clearPrivateKey = (PrivateKey) wrapper.unwrap(privateKeyToRecover, algorithm, Cipher.PRIVATE_KEY);
}

with the error: Unknown key type encoded key spec not recognized: failed to construct sequence from byte[]: Extra data detected in stream.
Using the default IV specified in RFC 3394 (which is A[0] = IV = A6A6A6A6A6A6A6A6) does not seem to solve the problem.

Could someone explain me how to fix this?

Thanks a lot for reading and taking time to answer Éric



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source