本主题有很多问题,但解决方法相同,但这对我无效。我有一个简单的测试加密。加密/解密本身起作用(只要我用字节数组本身而不是字符串来处理这个测试)。问题是不希望将它作为字节数组处理,而是作为字符串来处理,但是当我将字节数组编码为字符串并返回时,生成的字节数组与原始字节数组不同,因此解密不再有效。我在相应的字符串方法中尝试了以下参数: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);
}
}
您首先需要将字节转换为可以呈现为字符串的东西。通常通过转换为十六进制或base64。 – 2012-02-01 15:07:14
在转换为字符串之前和之后,您在字节数组中看到的实际区别是什么? – Herms 2012-02-01 15:08:10
@RogerLindsjö:感谢tipp。我会立即尝试。 – Bevor 2012-02-01 15:10:47