为什么这种简单的AES加密不起作用?

sat*_*sat 5 java encryption aes

为什么这种AES加密不起作用?我用Java编写它来测试,但我无法解密.解密后我得到了垃圾.为什么?它如此简单 - 在主要方法中,打印纯文本,加密,打印密文,解密,再次打印纯文本.难道我做错了什么?请帮我弄清楚问题所在.

import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AESTest { public static void main(String [] args) { try { String plainText = "Hello World!!!!!"; String encryptionKey = "E072EDF9534053A0B6C581C58FBF25CC"; System.out.println("Before encryption - " + plainText); String cipherText = encrypt(plainText, encryptionKey); System.out.println("After encryption - " + cipherText); String decrypted = decrypt(cipherText, encryptionKey); System.out.println("After decryption - " + decrypted); } catch (Exception e) { e.printStackTrace(); } } public static String encrypt(String plainText, String passkey) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE"); SecretKeySpec key = new SecretKeySpec(hexStringToByteArray(passkey), "AES"); cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(new byte[cipher.getBlockSize()])); String cipherText = new String(cipher.doFinal(plainText.getBytes())); return cipherText; } public static String decrypt(String cipherText, String passkey) throws Exception{ Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE"); SecretKeySpec key = new SecretKeySpec(hexStringToByteArray(passkey), "AES"); cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[cipher.getBlockSize()])); String plainText = new String(cipher.doFinal(cipherText.getBytes())); return plainText; } public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data; } }
Run Code Online (Sandbox Code Playgroud)

Hen*_*olm 5

密码的输出是一系列随机字节.您不能保证这些字节对于系统的默认编码中的字符串是有效的编码.所以这一行:

 String cipherText = new String(cipher.doFinal(.....));
Run Code Online (Sandbox Code Playgroud)

可能会丢失您需要解密的信息.

因此,您将无法在decrypt操作中重建正确的字节.例如,如果您的默认编码是UTF-8,则绝对不可能正确的密文String.getBytes()是甚至能够生成的密文.

  • 但OP在_encrypted_字节上使用`new String(...)`并尝试在解密操作中使用`String.getBytes()`重构它们.那无权工作. (3认同)