3

I use string for byte array transferring, but found something strange with it. Can somebody explain, why that's happen?

 byte[] bytes1 = new byte[]{-104, 73, 61, -15, -92, 109, 62, -99, 50, 82, 26, 87, 38, 110, -12, 49, -104, 73, 61, -15, -92, 109, 62, -99};
 byte[] bytes2 = new String(bytes1).getBytes();
 //for now bytes2 is equal to: {63, 73, 61, -15, -92, 109, 62, -99, 50, 82, 26, 87, 38, 110, -12, 49, 63, 73, 61, -15, -92, 109, 62, -99}
 System.out.println(Arrays.equals(bytes1, bytes2));//false
 for(int i = 0; i < bytes2.length; i++){
    if(bytes2[i] == 63) {
        bytes2[i] = -104;
    }
 }
 System.out.println(Arrays.equals(bytes1, bytes2));//true

ps bytes1 - this is triple des secret key bytes array. Each time it different, but it fail only in case, if bytes1 contain -104 values. Many thanks.

degr
  • 1,559
  • 1
  • 19
  • 37

1 Answers1

7

Strings are not byte arrays, byte arrays are not Strings. You can't use one to transfer the other directly.

Strings are logically char arrays. If you want to convert between chars and bytes, you need a character encoding, which specifies the mapping from chars to bytes, and vice versa.

The problem you are having here is that you are using the JVM's default character encoding, and trying to convert byte values which are not supported in that encoding.

If you must store a byte array in a string, you should do something like base64-encode it first.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • this work byte[] bytes2 = Base64.getDecoder().decode(new String(Base64.getEncoder().encode(bytes1))); – degr Nov 02 '15 at 09:17