Srinikhil Reddy
Srinikhil Reddy

Reputation: 15

Encrypting a AES key using RSA Key

I have written a code to encrypt a aes key and decrypt it but it dosent seem to be happening.Why is this so?

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair pair = keyGen.generateKeyPair();
PublicKey pubKey= pair.getPublic();
PrivateKey privateKey = pair.getPrivate();
Cipher c1 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
c1.init(Cipher.ENCRYPT_MODE, pubKey);
KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES");
aesKeyGenerator.init(256);               
 Key aesKey = rijndaelKeyGenerator.generateKey();                
Cipher symmetricCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] encodedKeyBytes = c1.doFinal(aeslKey.getEncoded());
SecretKey aesKey1 = new SecretKeySpec(encodedKeyBytes, "aes1");
Cipher dec = Cipher.getInstance("RSA/ECB/PKCS1Padding");
dec.init(Cipher.DECRYPT_MODE, privateKey);
symmetricCipher.init(Cipher.DECRYPT_MODE, aesKey1, spec);                   
if(aesKey.getEncoded() == dec.doFinal(c1.doFinal(aesKey.getEncoded())) )
{                            
    // Not reaching here but is supposed to 
}

Upvotes: 1

Views: 366

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 93948

On the line:

SecretKey aesKey1 = new SecretKeySpec(encodedKeyBytes, "aes1");

You are converting the still (RSA) encrypted aesKey to a SecretKey. At that spot you should have decrypted the key first. "aes1" is not any known type of key either.

Please try and separate the various wrapping (key encryption) and encryption statements into methods, and make separate methods for the unwrapping and decryption. Just throwing statements around is not going to get you anywhere. Try to make a methodical attempt to solve the problem at hand.

Upvotes: 2

Related Questions