0

I'm trying to convert a BigInteger privateKey to KEY, I found this piece of code and made some modifications like this:

            KeyFactory factory = KeyFactory.getInstance("RSA");
            RSAPrivateKeySpec spec;
            spec = new RSAPrivateKeySpec(modulus,privateKey);
            RSAPrivateKey priPEM = (RSAPrivateKey) factory.generatePrivate(spec);
            Cipher enc = Cipher.getInstance("RSA");
            enc.init(Cipher.WRAP_MODE, priPEM);
            byte[] encryptedKey = enc.wrap(priPEM);

However, the result is: Key is too long for wrapping

Exception in thread "main" java.security.InvalidKeyException: Key is too long for wrapping

I am using keysize (2048), I've tried 1024 and 512 but still the same output error.

Any idea on how can I get rid of this error?

Ash
  • 60
  • 10
  • Take a look at the answers to this question: http://stackoverflow.com/questions/19856324/exception-in-thread-main-java-security-invalidkeyexception-illegal-key-size-o – Breandán Dalton Sep 22 '14 at 09:39
  • Thank you for your contribution, but the link you provided has a different output error, anyway I did the steps in the solution but it ditn't fix the problem! – Ash Sep 22 '14 at 10:24
  • Seems like the encoded private key passed to wrap() method is longer than cipher's key modulus. – Abhiroop Sarkar Sep 22 '14 at 10:59

1 Answers1

0

Looks like this depends on RSA wrapper implementation. RSACipher sources I found at init call initializes internal buffer length with key.length() / 8. So, if toBeWrappedKey.length () > this value, than you get an exception. Moreover, this code using toBeWrappedKey.getEncoded (), so if getEncoded return null in case of some of providers, you get an "Could not obtain encoded key" exception. For sample, I've generated 512 key size to be exported, 4096-size exporting key and than wrap worked fine.