Encryption of Strings works, encryption of byte[] array type does not work

无人久伴 提交于 2019-11-30 01:38:45

What you're seeing is the result of the array's toString() method. It's not the content of the byte array. Use java.util.Arrays.toString(array) to display the content of the arrays.

[B is the type (array of bytes), and 1b10d42 is the hashCode of the array.

However my output is:

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

That's because you're printing out the result of calling toString() on a byte array. That's not going to show you anything useful, other than a suggestion of reference identity.

You should either just compare the plaintext data with the decrypted data byte for byte (which you can do with Arrays.equals(byte[], byte[])), or if you really want to display the contents, print out the hex or base64 representation. [Arrays.toString(byte\[\])][2] will give you a representation, but hex would probably be easier to read. There are loads of hex formatting classes in third-party libraries, or you could find a method on Stack Overflow.

Arpana

I know it's too late but I'm sharing my answer. Here I have used your code with some modification. Try below checker class to encrypt and decrypt a byte array.

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));
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!