Adr*_*ist 5 java arrays encryption aes
我正在使用以下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;
}
Run Code Online (Sandbox Code Playgroud)
检查员班级是:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但是我的输出是:
Plain Text : [B@1b10d42
Encrypted Text : [B@dd87b2
Decrypted Text : [B@1f7d134
Run Code Online (Sandbox Code Playgroud)
因此解密的文本与纯文本不同.我应该怎么做才能解决这个问题,因为我知道我在原始链接中尝试了这个例子并且它与字符串一起工作了?
但是我的输出是:
Run Code Online (Sandbox Code Playgroud)Plain Text : [B@1b10d42 Encrypted Text : [B@dd87b2 Decrypted Text : [B@1f7d134
那是因为你打印出调用toString()字节数组的结果.除了参考标识的建议之外,这不会向您展示任何有用的东西.
您应该只是将明文数据与解密后的数据字节进行比较(您可以使用Arrays.equals(byte[], byte[])),或者如果您确实要显示内容,请打印出hex或base64表示.[Arrays.toString(byte\[\])][2]会给你一个表示,但十六进制可能更容易阅读.第三方库中有大量的十六进制格式化类,或者您可以在Stack Overflow上找到一个方法.
你看到的是数组的toString()方法的结果.它不是字节数组的内容.使用java.util.Arrays.toString(array)显示阵列的内容.
[B是类型(字节数组),1b10d42是数组的hashCode.
| 归档时间: |
|
| 查看次数: |
14749 次 |
| 最近记录: |