Réda Bk Réda Bk - 6 months ago 8
Java Question

In Java, how to convert correctly byte[] to String to byte[] again?

I want to convert the result of a TEA encryption (a byte[]) to a String and then convert it again to a byte[] and retrieve the same byte[].

//Encryption in the sending side
String stringToEncrypt = "blablabla"
byte[] encryptedDataSent = tea.encrypt(stringToEncrypt.getBytes());
String dataToSend = new BigInteger(encryptedDataSent).toString());

//Decryption side in the reception side
byte[] encryptedDataReceived = new BigInteger(dataToSend).toByteArray();


However, when I try this :

System.out.println(new String(encryptedDataSent));

System.out.println(new String(encryptedDataReceived));

boolean equality = Arrays.equals(encryptedDataReceived,encryptedDataSent);
System.out.println("Are two byte arrays equal ? : " + equality);


The output is :


&h�7�"�PAtj݄�I��Z`H-jK�����f

&h�7�"�PAtj݄�I��Z`H-jK�����f

Are two byte arrays equal ? : false


So, it looks like the two byte[] are the same when we print it but they are not exactly the same as we see "false" and this is a problem for the decryption that I perform after that.

I also tried to send a
String with new String(byte[])
but it has the same problem when we want to convert it back to a byte[]

I want to have exactly the same byte[] in the beginning and after the conversion byte[]->String->byte[]

Do you have a solution or understand what I do wrong in my conversion ?

Answer

Don't try to convert from the byte[] to String as if it were regular encoded text data - it isn't. It's an arbitrary byte array.

The simplest approaches are to convert it to base64 or hex - that will result in ASCII text which can be reversibly decoded back to the same binary data. For example, using a public domain base64 encoder:

String dataToSend = Base64.encodeBytes(encryptedDataSent);
...
byte[] encryptedDataReceived = Base64.decode(receivedText);