Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

byte array to string and inverse : recoverded byte array is NOT match to original byte array in Java

I converted a byte array to string as follow, in Java:

String str_bytearray = new String(bytearray_original);

and then, I recovered original byte array using string, as follow:

byte[] bytearray_recovered = str_bytearray.getBytes();

but I wondered when I compared bytearray_original and bytearray_recovered. the result is as follow:

[48, 89, 48, 19, 6, 7, 42, -122, 72, -50, 61, 2, 1, 6, 8, 42, -122, 72, -50, 61, 3, 1, 7, 3, 66, 0, 4, 100, -27, 48, -31, 13, -33, 107, -90, 91, -9, 119, 121, -73, 83, -105, 51, -87, -109, -84, 99, 115, -123, 119, -117, -1, -62, 71, -32, 99, 4, -103, -115, -47, 113, -83, 8, -91, 14, -74, 113, -40, -26, 50, 111, 95, 71, -9, 112, 120, 16, 0, 113, -80, 124, -71, 53, -97, 69, -85, 38, -112, -30, -110, 115]

[48, 89, 48, 19, 6, 7, 42, -122, 72, -50, 61, 2, 1, 6, 8, 42, -122, 72, -50, 61, 3, 1, 7, 3, 66, 0, 4, 100, -27, 48, -31, 13, -33, 107, -90, 91, -9, 119, 121, -73, 83, -105, 51, -87, -109, -84, 99, 115, -123, 119, -117, -1, -62, 71, -32, 99, 4, -103, 63, -47, 113, -83, 8, -91, 14, -74, 113, -40, -26, 50, 111, 95, 71, -9, 112, 120, 16, 0, 113, -80, 124, -71, 53, -97, 69, -85, 38, 63, -30, -110, 115]

as you can see, two bytes are different from original byte array, that is -115 to 63 and -112 to 63. Is it possible to solve this problem?

Note: In fact both original and recovered byte array are a public key. First public key is converted to string to store in a file, and then after reading string value of the public key, it should be recovered to verify the signature.

The bytearray_original is generated as follow:

PublicKey signPublicKey = keypair.getPublic(); 
byte [] bytearray_original = signPublicKey.getEncoded();

I appreciate any help.

Regards

like image 741
Questioner Avatar asked Dec 09 '22 02:12

Questioner


1 Answers

You cannot convert an arbitrary sequence of bytes to String and expect the reverse conversion to work. You will need to use an encoding like Base64 to preserve an arbitrary sequence of bytes. (This is available from several places -- built into Java 8, and also available from Guava and Apache Commons.)

For example, with Java 8,

String encoded = Base64.getEncoder().encodeToString(myByteArray);

is reversible with

byte[] decoded = Base64.getDecoder().decode(encoded);
like image 177
Louis Wasserman Avatar answered Dec 11 '22 10:12

Louis Wasserman