alex.agra...@gmail.com wrote, On 2008-12-21 08:02:

> I'm working with NSS from JAVA (via JAVA 6 PKCS11 provider on RHEL 5).
> My NSS database is  configured for FIPS-140 mode. And I try to wrap/
> unwrap AES key with RSA public/private key pair as follows:
> 
>     // open NSS keystore
>     char[] nssDBPassword = {'f', 'i', 'p', 's', '1', '4', '0', '-', '2'};
>     KeyStore ks = KeyStore.getInstance("PKCS11");
>     ks.load(null, nssDBPassword);
>     Provider p = ks.getProvider();
> 
>     // generate RSA key pair
>     KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", p);
>     KeyPair keyPair = keyPairGen.generateKeyPair();
> 
>     // generate AES key
>     KeyGenerator keyGen = KeyGenerator.getInstance("AES", p);
>     keyGen.init(128);
>     Key rawKey = keyGen.generateKey();
>     System.out.println("raw Key : " + rawKey);
> 
>     // wrap key
>     Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", p);
>     cipher.init(Cipher.WRAP_MODE, keyPair.getPublic());
>     byte[] wrappedData = cipher.wrap(rawKey);
> 
>     // unwrap key
>     cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", p);
>     cipher.init(Cipher.UNWRAP_MODE, keyPair.getPrivate());
>     unwrappedKey = cipher.unwrap(wrappedData, "AES", Cipher.SECRET_KEY);
> 
>     // encode data
>     cipher = Cipher.getInstance("AES/CBC/NoPadding", p);
>     cipher.init(Cipher.ENCRYPT_MODE, unwrappedKey);
> 
> The wrap/unwrap code seems to work fine. But when I attempt to perform
> encoding with the unwrapped key - I get the following exception
> (which, as far as I understand, seems to suggest that key doesn't
> reside inside NSS crypto token):
> 
>   raw Key : SunPKCS11-NSScrypto AES secret key, 128 bits (id 12, session 
> object, sensitive, extractable)
>   java.security.InvalidKeyException: Could not create key
>       at sun.security.pkcs11.P11SecretKeyFactory.createKey 
> (P11SecretKeyFactory.java:226)
>       at sun.security.pkcs11.P11SecretKeyFactory.convertKey 
> (P11SecretKeyFactory.java:131)
>       at sun.security.pkcs11.P11Cipher.engineGetKeySize(P11Cipher.java:582)
>       at javax.crypto.Cipher.b(DashoA13*..)
>       at javax.crypto.Cipher.a(DashoA13*..)
>       at javax.crypto.Cipher.init(DashoA13*..)
>       at javax.crypto.Cipher.init(DashoA13*..)
>       at EncryptionTest.main(EncryptionTest.java:88)

Are you sure this is not coming from the cipher.unwrap call?
If you add a line of code to print info about the unwrapped key,
does it show that key to be in the NSS token?

> Can anybody tell me what am I doing wrong? Or, may be, point me to
> some working JAVA code that performs wrap/unwrap of the key in NSS
> token?

Maybe one of our seasoned Java veterans can help with those questions.
_______________________________________________
dev-tech-crypto mailing list
dev-tech-crypto@lists.mozilla.org
https://lists.mozilla.org/listinfo/dev-tech-crypto

Reply via email to