Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 491
red.and.black Avatar asked Apr 01 '26 15:04

red.and.black


2 Answers

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);
like image 77
Jon Skeet Avatar answered Apr 04 '26 14:04

Jon Skeet


Try to use in the decryption byte[] encode = Base64.encode(bytesToStore, Base64.DEFAULT)

like image 24
Pavel Poley Avatar answered Apr 04 '26 14:04

Pavel Poley