更新时间:2022-03-25 23:13:13
实际上,其中存在很多错误您尝试使用非对称RSA来包装和解开对称密钥,所以我将其清除(我的计算机上没有Bouncy Castle,因此我使用了默认的Sun提供程序,请在需要时随时添加 BC):
Actually there are quite a few errors in your attempt to wrap and unwrap a symmetric key using asymmetric RSA, so I cleaned it up (I have no Bouncy Castle on my machine, so I used the default Sun providers, feel free to add "BC" where needed):
KeyGenerator kgenerator = KeyGenerator.getInstance("AES");
SecureRandom random = new SecureRandom();
kgenerator.init(128, random);
Key aeskey = kgenerator.generateKey();
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024, random);
KeyPair kpa = kpg.genKeyPair();
PublicKey pubKey = kpa.getPublic();
PrivateKey privKey = kpa.getPrivate();
// Encrypt the generated Symmetric AES Key using RSA cipher
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
rsaCipher.init(Cipher.WRAP_MODE, pubKey);
byte[] encryptedSymmKey = rsaCipher.wrap(aeskey);
// RSA Decryption of Encrypted Symmetric AES key
rsaCipher.init(Cipher.UNWRAP_MODE, privKey);
Key decryptedKey = rsaCipher.unwrap(encryptedSymmKey, "AES", Cipher.SECRET_KEY);
System.out.println("Decrypted Key Length: " + decryptedKey.getEncoded().length * 8); // -> 128