【发布时间】:2013-04-26 15:26:55
【问题描述】:
由于 byte[]-String 转换,我在加密和解密一些 AES 消息时遇到了一些麻烦...我发现 a[9]!=c[9] 的方式非常有趣(在调试时看到了差异)
try {
String encryptionKey = "1234567890123456";
String plaintext = "1234567890123456";
System.out.println("key: " + encryptionKey);
System.out.println("plain: " + plaintext);
byte[] a = aes.encrypt(plaintext, encryptionKey);
String b = new String(a);
byte[] c = b.getBytes();
String decrypted = new String(aes.decrypt(c, encryptionKey));
System.out.println("decrypt: " + decrypted);
} catch (Exception e) {
e.printStackTrace();
}
}
public byte[] encrypt(String plainText, String encryptionKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes()));
return cipher.doFinal(plainText.getBytes());
}
【问题讨论】:
-
一个字节是 8 位。 Java
char是 16 位。当您将任意 8 位字节数组转换为 Java 字符串(反之亦然)时,您通常会遇到一些“映射”,因为 8 位数据将被解释为 UTF8 或其他字节 > 127 的字符编码被视为特殊字符并以某种方式扩展。如果您想将“纯二进制”(加密数据通常是“纯二进制”)作为字符串传输,则需要使用 Base64 编码或类似的编码。 -
@Fildor 如果我使用:String decrypted = new String(aes.decrypt(c, encryptionKey));结果将是:密钥:1234567890123456 普通:1234567890123456 解密:ń?Ľ·w?q9rÁK?y
-
你试过使用 UTF-8 编码吗?