javarsapkcs#11hardware-security-moduleoaep

Wrap AES key with RSA public key - CKM_RSA_PKCS_OAEP


I am using iaik pkcs11 java trying to wrap an AES key with RSA public key.

Can someone please help me what is the issue with above params/code?

I am trying to wrap an AES key with RSA public key. Getting issue as Mechanism invalid

    Mechanism mechanism = Mechanism.get(PKCS11Constants.CKM_RSA_PKCS_OAEP);
    RSAPkcsOaepParameters rsaPkcsOaepParameters =
            new RSAPkcsOaepParameters(
                    Mechanism.get(PKCS11Constants.CKM_SHA256),
                    RSAPkcsParameters.MessageGenerationFunctionType.SHA256,
                    RSAPkcsOaepParameters.SourceType.EMPTY,
                    null);
    mechanism.setParameters(rsaPkcsOaepParameters);

    session.wrapKey(mechanism, wrappingKey, keyToWrap);

wrappingKey is an RSA public key handle and keyToWrap is an AES key

iaik.pkcs.pkcs11.wrapper.PKCS11Exception: CKR_MECHANISM_PARAM_INVALID
    at iaik.pkcs.pkcs11.wrapper.PKCS11Implementation.C_WrapKey(Native Method) ~[iaik-pkcs11-wrapper-1.6.4.jar:?]
    at iaik.pkcs.pkcs11.Session.wrapKey(Session.java:1433) ~[iaik-pkcs11-wrapper-1.6.4.jar:?]

Solution

  • As far as I know you should use RSAPkcsOaepParameters.SourceType.DATA_SPECIFIED (CKZ_DATA_SPECIFIED as specified in PKCS#11):

    public static Mechanism getRsaOaepSha256Mechanism() {
        Mechanism mechanism = Mechanism.get(PKCS11Constants.CKM_RSA_PKCS_OAEP);
        RSAPkcsOaepParameters rsaPkcsOaepParameters =
                new RSAPkcsOaepParameters(
                        Mechanism.get(PKCS11Constants.CKM_SHA256),
                        RSAPkcsParameters.MessageGenerationFunctionType.SHA256,
                        RSAPkcsOaepParameters.SourceType.DATA_SPECIFIED,
                        null);
        mechanism.setParameters(rsaPkcsOaepParameters);
        return mechanism;
    }
    

    Good luck with your project!