Java AES/CBC 解密后初始字节不正确
问题:
尝试时在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.
解决方案:
由于在处理加密/解密数据时缺少 Base64 编码/解码,导致解密字符串中的初始字节不正确。要解决此问题,应在传输加密字节之前对加密字节进行 Base64 编码,并在解密之前对接收到的加密字节进行 Base64 解码。
更新示例:
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中文网其他相关文章!