字符串加密工作,byte 数组类型的加密不起作用

我正在使用以下LINK进行加密,并使用Strings进行了尝试并且它有效。 但是,由于我正在处理图像,我需要使用字节数组进行加密/解密过程。 所以我将该链接中的代码修改为以下内容:

public class AESencrp { private static final String ALGO = "AES"; private static final byte[] keyValue = new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't', 'S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' }; public static byte[] encrypt(byte[] Data) throws Exception { Key key = generateKey(); Cipher c = Cipher.getInstance(ALGO); c.init(Cipher.ENCRYPT_MODE, key); byte[] encVal = c.doFinal(Data); //String encryptedValue = new BASE64Encoder().encode(encVal); return encVal; } public static byte[] decrypt(byte[] encryptedData) throws Exception { Key key = generateKey(); Cipher c = Cipher.getInstance(ALGO); c.init(Cipher.DECRYPT_MODE, key); byte[] decValue = c.doFinal(encryptedData); return decValue; } private static Key generateKey() throws Exception { Key key = new SecretKeySpec(keyValue, ALGO); return key; } 

检查员class级是:

 public class Checker { public static void main(String[] args) throws Exception { byte[] array = new byte[]{127,-128,0}; byte[] arrayEnc = AESencrp.encrypt(array); byte[] arrayDec = AESencrp.decrypt(arrayEnc); System.out.println("Plain Text : " + array); System.out.println("Encrypted Text : " + arrayEnc); System.out.println("Decrypted Text : " + arrayDec); } } 

但是我的输出是:

 Plain Text : [B@1b10d42 Encrypted Text : [B@dd87b2 Decrypted Text : [B@1f7d134 

因此解密的文本与纯文本不同。 我应该怎么做才能解决这个问题,因为我知道我在原始链接中尝试了这个例子并且它与字符串一起工作了?

你看到的是数组的toString()方法的结果。 它不是字节数组的内容。 使用java.util.Arrays.toString(array)显示java.util.Arrays.toString(array)的内容。

[B是类型(字节数组), 1b10d42是数组的hashCode。

但是我的输出是:

 Plain Text : [B@1b10d42 Encrypted Text : [B@dd87b2 Decrypted Text : [B@1f7d134 

那是因为你打印出在字节数组上调用toString()的结果。 除了参考标识的建议之外,这不会向您展示任何有用的东西。

您应该只是将明文数据与字节的解密数据字节进行比较(您可以使用Arrays.equals(byte[], byte[]) ),或者如果您确实要显示内容,请打印出hex或base64表示。 [Arrays.toString(byte\[\])][2]会给你一个表示,但hex可能更容易阅读。 第三方库中有大量的hex格式化类,或者您可以在Stack Overflow上找到一个方法。

我知道现在为时已晚,但我正在分享我的答案。 在这里,我使用了一些修改代码。 尝试使用以下checker类来加密和解密字节数组。

检查员class级:

 public class Checker { public static void main(String[] args) throws Exception { byte[] array = "going to encrypt".getBytes(); byte[] arrayEnc = AESencrp.encrypt(array); byte[] arrayDec = AESencrp.decrypt(arrayEnc); System.out.println("Plain Text : " + array); System.out.println("Encrypted Text : " + arrayEnc); System.out.println("Decrypted Text : " + new String(arrayDec)); } }