问题:
无法使用 3DES 加密成功加密和解密字符串由于代码中反复出现错误
解决方案:
为了解决这个问题,我们来分析一下提供的代码:
public class TripleDESTest { // ... public byte[] encrypt(String message) { // ... final byte[] plainTextBytes = message.getBytes("utf-8"); final byte[] cipherText = cipher.doFinal(plainTextBytes); final String encodedCipherText = new sun.misc.BASE64Encoder().encode(cipherText); return cipherText; } // ... }
Base64 编码误解:
最初,代码包含行 Final String UpdatedCipherText = new sun.misc.BASE64Encoder().encode(cipherText);用于在返回密文之前对密文进行 Base64 编码。但是,由于解密方法中未使用 Base64 编码,因此密文应直接作为字节数组返回。
打印原始字节数组:
The代码将加密和解密的数据打印为字节数组:System.out.println(codedtext);和 System.out.println(decodedtext);。这不会提供有意义的输出,因为字节数组不会呈现为人类可读的值。要显示实际解密的文本,请使用 new String(plainText, "UTF-8") 将其转换为字符串。
更正代码:
import java.security.MessageDigest; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class TripleDESTest { public static void main(String[] args) throws Exception { String text = "kyle boon"; byte[] codedtext = new TripleDESTest().encrypt(text); String decodedtext = new TripleDESTest().decrypt(codedtext); System.out.println(decodedtext); } public byte[] encrypt(String message) throws Exception { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9" .getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3