Java – byte[] to string to byte array conversion did not work fine in java

bytec++java

I have a byte array initialised like this:

public static byte[] tmpIV =  {0x43, (byte)0x6d, 0x22, (byte)0x9a, 0x22,
                         (byte)0xf8, (byte)0xcf, (byte)0xfe, 0x15, 0x21,
                         (byte)0x0b, 0x38, 0x01, (byte)0xa7, (byte)0xfc, 0x0e};

If I print it it gives me

67   109    34      -102       34     -8          -49      -2      21      33
11    56    1       -89       -4      14

Then I converted the whole byte array into string and sent to my friend.

String str = new String(tmpIV);

My friend is a C# programmer

So my friend gets some other data. How my friend will get the same data as I have sent.
Also In Java if I reconvert the above string into byte array I am not getting the exact one that I have sent:

 67     109        34        -17        -65      -67      34       -17     -65       -67
-17     -65        -67        -17         -65    -67      21       33    11     56      1
-17      -65      -67         -17       -65       -67   

Best Solution

The problem is that you've converted the byte array into a string in the platform default encoding.

If this is arbitrary binary data (which it appears to be) then you shouldn't use any normal character encoding to convert it into a string - use base64 instead.

Using base64 from Java isn't particularly easy (because it's not in the standard libraries AFAIK) but there are various 3rd party libraries you can use, such as the one in the Apache Commons Codec library.

On the C# side it'll be a lot easier - just use:

byte[] data = Convert.FromBase64String(text);