Java AES 解密:末尾的随机字符和消息
Java AES Decryption: random chars & message at the end
我在使用 AES 解密邮件时遇到问题。最后,当我期待一条消息时,例如
ala123
相反,我收到了这样的东西:
...6�b}�k�8�vFP�8~%��_zժF��FW��O_e���ó������������ala123
我传递给加密的消息构建为:
- 密钥是来自 AES_TOKEN
的 SHA-256
- 密码IV是一些字符,然后存储在消息中(在beginnig)
- 解密的消息被打包成 Base64
问题是为什么最后我最终收到了我预期的消息,但一开始却有很多垃圾字符?
我的加密密码是:
private static final String AES_TOKEN = "my_very_secret_token";
// encrypted is base64 string
public String decrypt(String encrypted) throws Exception {
byte[] decrypted = Base64.getDecoder().decode(encrypted);
return new String(aesDecrypt(decrypted), "UTF-8");
}
private byte[] aesDecrypt(byte[] message) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] token = MessageDigest.getInstance("SHA-256").digest(AES_TOKEN.getBytes());
SecretKeySpec secretKey = new SecretKeySpec(token, "AES");
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOf(message, 16));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
return cipher.doFinal(message);
}
看起来您没有在读入 iv
后从 message
开头删除 IV。这可以解释解密消息开头的垃圾。
我在使用 AES 解密邮件时遇到问题。最后,当我期待一条消息时,例如
ala123
相反,我收到了这样的东西:
...6�b}�k�8�vFP�8~%��_zժF��FW��O_e���ó������������ala123
我传递给加密的消息构建为:
- 密钥是来自 AES_TOKEN 的 SHA-256
- 密码IV是一些字符,然后存储在消息中(在beginnig)
- 解密的消息被打包成 Base64
问题是为什么最后我最终收到了我预期的消息,但一开始却有很多垃圾字符?
我的加密密码是:
private static final String AES_TOKEN = "my_very_secret_token";
// encrypted is base64 string
public String decrypt(String encrypted) throws Exception {
byte[] decrypted = Base64.getDecoder().decode(encrypted);
return new String(aesDecrypt(decrypted), "UTF-8");
}
private byte[] aesDecrypt(byte[] message) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] token = MessageDigest.getInstance("SHA-256").digest(AES_TOKEN.getBytes());
SecretKeySpec secretKey = new SecretKeySpec(token, "AES");
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOf(message, 16));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
return cipher.doFinal(message);
}
看起来您没有在读入 iv
后从 message
开头删除 IV。这可以解释解密消息开头的垃圾。