小编典典

字符串加密有效,字节[]数组类型的加密无效

java

我正在使用以下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;
    }

而检查器类是:

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

因此,解密后的文本与纯文本不同。知道我在原始链接中尝试了该示例并且该示例可与Strings一起使用时,该怎么办才能解决此问题?


阅读 139

收藏
2020-11-13

共1个答案

小编典典

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

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

2020-11-13