Vikas Rai
Vikas Rai

Reputation: 87

How to wrap a RSA Key with AESWRAP mode

I am suppose to wrap my RSA Private Key with AESWrap mode(following RFC 3394). However I am getting exception saying "length of the to be wrapped key should be multiples of 8 bytes". I believe this is majorly because RSA PrivateKey is in DER format and hence the exception is being thrown. Please suggest how to resolve this.


    SecretKey swkKeySpec = new SecretKeySpec(KEK, 0, swkKey.length, "AES");///KEK is a 256 bit AES key used for wrapping.
    cipher = Cipher.getInstance("AESWrap", "SunJCE");
    cipher.init(Cipher.WRAP_MODE, swkKeySpec);

    byte[] key = keyAttributes.getPrivateKey() ///This returns private key in encoded format which is to be wrapped.
    KeyFactory factory = KeyFactory.getInstance("RSA"); // throws NoSuchAlgorithmException
    PrivateKey privateKey  = factory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
    log.debug("key.length: {}", key.length); ///this gives 634.
    wrappedAppKey = cipher.wrap(privateKey); ///exception thrown at this point`

Upvotes: 1

Views: 1618

Answers (1)

Alexandre Fenyo
Alexandre Fenyo

Reputation: 4809

RFC-5649 (Advanced Encryption Standard (AES) Key Wrap with Padding Algorithm) has been published to handle cases for which the key material is not a multiple of 64 bits.

BouncyCastle, a free Java library implementing many cryptographic algorithms, offers a wrap engine that supports the RFC-5649 key wrapping algorithm. Therefore, you may use this library to avoid the Java exception you encounter.

Note that what we commonly call an RSA key of 2048 bits, for instance, is not simply made of an array of 256 bytes. It is made of two prime numbers such that their product can be stored in a array of 256 bytes, it is also made of a private exponent that is lower than the aforementioned product. Depending on the way the private key material is stored in a file, some other public data may be encapsulated in the file, such as the public exponent. So the private key material of an RSA key of 2048 bits may not be stored with 256 bytes.

Upvotes: 2

Related Questions