Java AES/CBC 解密後初始位元組不正確
問題:
嘗試
問題:嘗試
問題:import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AESEncryptionExample { public static void encryptDecryptString() { try { String key = "mySecretKey"; String value = "This is a test message"; String initVector = "initializationVector"; // 16-byte (128-bit) initialization vector IvParameterSpec iv = new IvParameterSpec(initVector.getBytes()); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES"); // Create encrypt cipher Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); encryptCipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encryptedBytes = encryptCipher.doFinal(value.getBytes()); // Create decrypt cipher Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); decryptCipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] decryptedBytes = decryptCipher.doFinal(encryptedBytes); System.out.println("Original: " + value); System.out.println("Decrypted: " + new String(decryptedBytes)); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { encryptDecryptString(); } }
Result: `£eB6O�geS��i are you? Have a nice day.
以下程式碼示範了這個問題:
執行此程式碼時,解密的輸出可能會出現類似的情況至:解決方案:
import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class CipherAESBase64 { public static void encryptDecryptString() { try { String key = "mySecretKey"; String value = "This is a test message"; String initVector = "initializationVector"; // 16-byte (128-bit) initialization vector IvParameterSpec iv = new IvParameterSpec(initVector.getBytes()); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES"); // Create encrypt cipher Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); encryptCipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encryptedBytes = encryptCipher.doFinal(value.getBytes()); // Encode the encrypted bytes into a Base64 string String encryptedString = Base64.getEncoder().encodeToString(encryptedBytes); // Create decrypt cipher Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); decryptCipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); // Decode the encrypted Base64 string into bytes byte[] decryptedBytes = Base64.getDecoder().decode(encryptedString); // Decrypt the decoded bytes byte[] decryptedBytes = decryptCipher.doFinal(decryptedBytes); System.out.println("Original: " + value); System.out.println("Decrypted: " + new String(decryptedBytes)); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { encryptDecryptString(); } }
以上是為什麼 Java AES/CBC 解密後初始位元組不正確,如何修復?的詳細內容。更多資訊請關注PHP中文網其他相關文章!