我用 AES 密钥加密了 AES 密钥,将密钥作为字符串存储在数据库中,当我尝试解密我得到的密钥时:

I have encrypted AES Key with AES Key,Stored the Key as String in DataBase, when i try to decrypt the Key i get :

javax.crypto.IllegalBlockSizeException: 
    Input length must be multiple of 16 when decrypting with padded cipher

请检查代码的重要部分:

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecretKey secKey = (SecretKey) keyGen.generateKey();
SecretKey secKey1 = (SecretKey) keyGen1.generateKey();

byte[] stringKey=secKey.getEncoded();

cipher.init(Cipher.ENCRYPT_MODE, secKey1);
byte[] DykeyBytes = cipher.doFinal(stringKey);

StringBuffer sbselect2=new StringBuffer();
sbselect2.append("SELECT keylock FROM ");
sbselect2.append(UserConstants.USER_DETAILS_TABLE_NAME1);
sbselect2.append(" where Username='" + un + "'");
ps2=conn.prepareStatement(sbselect2.toString());
ResultSet rs1 =ps2.executeQuery();
rs1.next();
String Enkey = rs1.getString("keylock");

System.out.println("Encrypted+Encoded key from current user "+Enkey);
rs1.close();

//decrypting the DB stored Key
Cipher cipher2 = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher2.init(Cipher.DECRYPT_MODE, singlekey );
byte[] dynamicKey = Enkey.getBytes("UTF8");
// below is where the error points  to at user.dao.UserDao.isRegisteredUser(UserDao.java:313)
byte[] decryptedBytes = cipher2.doFinal(dynamicKey);

Object DeKey = new String(decryptedBytes);//under check
SecretKeySpec key = new SecretKeySpec(decryptedBytes, "AES");

大家好今天我很高兴我尝试了几种类型的逻辑,最后我找到了答案答案,我相信我是第一个得到它的人。嘻嘻欢呼。从上午 10 点开始工作到下午 6 点,我的努力得到了回报。

这是过程

Secret Key生成---Base64Enocder---用相似的secretkey加密--Base64Encoded--转换成String--存入数据库---取出String---Base64Decoder---解密--Base64Decoder-- SecretKeySpec--walla her is the key

输出: 加密前Key: javax.crypto.spec.SecretKeySpec@178e7 。 base64: UKcvVLp9L51xxHHyLIRrgQ== 。 base64double: wu8CBPMELHgp6WAGGFgHGWjPXn4MRibeZ9IKGRTpjJE= . base64 加密后: wu8CBPMELHgp6WAGGFgHGWjPXn4MRibeZ9IKGRTpjJE= 。 解密 base64double 后:[B@1cfe433。 解密 base64 后: [B@18f11d3 . 在 base64decoder 和 keyspec 之后:javax.crypto.spec.SecretKeySpec@178e7 .