Java AES解密: random chars & message at the end

标签 java encryption cryptography aes

我在使用 AES 解密消息时遇到问题。最后,当我期待一条消息时,例如

ala123

相反,我收到的是这样的东西:

...6�b}\7�k�8�vFP�8~%��_zժF��FW��O_e���ó������������ala123

我传递给加密的消息构建为:

  • key 是来自 AES_TOKEN 的 SHA-256
  • 密码 IV 是一些字符,然后将其存储在消息中(在开头)
  • 解密的消息被封装成 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。这可以解释解密消息开头的垃圾。

关于Java AES解密: random chars & message at the end,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34594719/

相关文章:

javascript - AES 128 解密 : First char of CryptoJS. enc.Latin1 格式错误

python - 如何将 AES 模式从一种迁移到另一种?

python - Pycrypto AES-CTR 实现

java - Spring MVC 响应体

java - Tomcat 404 : The requested resource is not available

java - Android上的音频流

php - 在 Apache 中不使用 SSL 在服务器之间发送加密数据

java - 使用证书对 pdf 进行 iText 加密会导致 bouncycaSTLe 错误

java - 点击 Android 屏幕解决媒体跳过问题,如何解决?

java - 在 Java 中将 ISO7816d4Padding 与 BlockCipher 结合使用