問題:
無法使用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中文網其他相關文章!