且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 AES 和 Base64 编码加密和解密

更新时间:2023-02-17 17:19:02

您的加密命令: getBytes, encrypt, encode, toString
您的解密顺序(错误*): getBytes、decrypt、decode、toString

两个问题:

  1. 正如有人已经提到的,您应该颠倒解密操作的顺序.你没有这样做.
  2. encrypt 给你 16 个字节,编码 24 个字节,但 toString 给你 106 个字节.与占用额外空间的无效字符有关.

注意:另外,您不需要调用 generateKey() 两次.

Note: Also, you don't need to call generateKey() twice.

解决问题 #1 使用相反的解密顺序.
解密的正确顺序: getBytes,decode,decrypt,toString

Fix problem #1 by using the reverse order for decryption.
Correct order for decrypt: getBytes, decode, decrypt, toString

修复问题 #2,将 xxx.toString() 替换为 new String(xxx).在加密和解密函数中执行此操作.

Fix problem #2 by replacing xxx.toString() with new String(xxx). Do this in both the encrypt and decrypt functions.

您的解密应如下所示:

c.init(Cipher.DECRYPT_MODE, key)
val decodedValue = new Base64().decode(encryptedValue.getBytes())
val decryptedVal = c.doFinal(decodedValue)
return new String(decryptedVal)

这应该会给你回dude5"

This should give you back "dude5"