使用RSA密钥加密AES密钥

时间:2014-05-12 10:59:50

标签: java encryption aes rsa

我已经编写了一个代码来加密aes密钥并对其进行解密,但它似乎正在发生。为什么会这样?

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 
}

1 个答案:

答案 0 :(得分:2)

在线:

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

您正在将静止(RSA)加密的aesKey转换为SecretKey。在那个地方你应该首先解密密钥。 "aes1"也不是任何已知类型的密钥。

请尝试将各种包装(密钥加密)和加密语句分离为方法,并为解包和解密制作单独的方法。只是抛出陈述并不会让你随处可见。尝试使用有条不紊的尝试解决手头的问题。