red.and.black
red.and.black

Reputation: 33

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 ?

Upvotes: 3

Views: 3505

Answers (4)

S. Kadakov
S. Kadakov

Reputation: 919

try to specify charset explicitly. UTF-8 is ok for major cases:

public static void main(String[] args) {
    String in = "幸福";
    try {
        byte[] bytes = in.getBytes("utf-8");
        String out = new String(bytes, "utf-8");
        System.out.println(in + " -> " + out);
        System.out.println("equals: " + out.equals(in));
    } catch (UnsupportedEncodingException unsupportedEncodingException) {
        // do something
    }
}

Please note that you will get exactly the same result while you byte array remains unchanged.

Upvotes: -2

Pavel Poley
Pavel Poley

Reputation: 5587

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500535

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

Upvotes: 4

user207421
user207421

Reputation: 310913

You can't. String is not a container for binary data. It is a container for UTF-16 characters. The round trip between chars and bytes is nowhere guaranteed.

Upvotes: 0

Related Questions