【发布时间】:2012-02-24 06:18:40
【问题描述】:
这个主题有很多问题,相同的解决方案,但这对我不起作用。我有一个简单的加密测试。加密/解密本身有效(只要我用字节数组本身而不是字符串来处理这个测试)。问题是不想将其作为字节数组而是作为字符串处理,但是当我将字节数组编码为字符串并返回时,生成的字节数组与原始字节数组不同,因此解密不再起作用。我在对应的字符串方法中尝试了以下参数:UTF-8、UTF8、UTF-16、UTF8。它们都不起作用。生成的字节数组与原始数组不同。任何想法为什么会这样?
加密器:
public class NewEncrypter
{
private String algorithm = "DESede";
private Key key = null;
private Cipher cipher = null;
public NewEncrypter() throws NoSuchAlgorithmException, NoSuchPaddingException
{
key = KeyGenerator.getInstance(algorithm).generateKey();
cipher = Cipher.getInstance(algorithm);
}
public byte[] encrypt(String input) throws Exception
{
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] inputBytes = input.getBytes("UTF-16");
return cipher.doFinal(inputBytes);
}
public String decrypt(byte[] encryptionBytes) throws Exception
{
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] recoveredBytes = cipher.doFinal(encryptionBytes);
String recovered = new String(recoveredBytes, "UTF-16");
return recovered;
}
}
这是我尝试的测试:
public class NewEncrypterTest
{
@Test
public void canEncryptAndDecrypt() throws Exception
{
String toEncrypt = "FOOBAR";
NewEncrypter encrypter = new NewEncrypter();
byte[] encryptedByteArray = encrypter.encrypt(toEncrypt);
System.out.println("encryptedByteArray:" + encryptedByteArray);
String decoded = new String(encryptedByteArray, "UTF-16");
System.out.println("decoded:" + decoded);
byte[] encoded = decoded.getBytes("UTF-16");
System.out.println("encoded:" + encoded);
String decryptedText = encrypter.decrypt(encoded); //Exception here
System.out.println("decryptedText:" + decryptedText);
assertEquals(toEncrypt, decryptedText);
}
}
【问题讨论】:
-
您首先需要将字节转换为可以显示为字符串的内容。通常通过转换为 hex 或 base64。
-
在转换为字符串之前和之后,您在字节数组中看到的实际差异是什么?
-
@Roger Lindsjö:感谢您的提示。我马上试试。
-
@Herms: 一个例子 -> encryptedByteArray:[B@7df17e77, 编码:[B@79a5f739
-
那些看起来像内存地址,而不是数组的实际内容。
标签: java string encryption bytearray