Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using the following LINK for encryption and tried it with Strings and it worked. However, since I am dealing with images, I needed the encryption/decryption process to happen with byte arrays. So I modified the code in that link to the following:

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;
    }

and the checker class is:

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);
    }
}

However my output is:

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

So the decrypted text is not the same as plain text. What should I do to fix this knowing that I tried the example in the original link and it worked with Strings?

like image 671
Adroidist Avatar asked May 12 '12 10:05

Adroidist


People also ask

Is a string a byte array?

Remember that a string is basically just a byte array For example, the following code iterates over every byte in a string and prints it out as both a string and as a byte.

What is string encryption?

Encrypts a string, using a symmetric key-based algorithm, in which the same key is used to encrypt and decrypt a string. The security of the encrypted string depends on maintaining the secrecy of the key, and the algorithm choice.


1 Answers

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.

like image 51
JB Nizet Avatar answered Oct 27 '22 17:10

JB Nizet