问题:
无法使用 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 generatedCipherText = 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 < 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); final byte[] plainTextBytes = message.getBytes("utf-8"); final byte[] cipherText = cipher.doFinal(plainTextBytes); return cipherText; } public String decrypt(byte[] 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 < 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); decipher.init(Cipher.DECRYPT_MODE, key, iv); final byte[] plainText = decipher.doFinal(message); return new String(plainText, "UTF-8"); } }
以上是为什么我的 Java 3DES 加密/解密失败?的详细内容。更多信息请关注PHP中文网其他相关文章!