tags:

views:

1770

answers:

2

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
+10  A: 

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);
Jon Skeet
A: 

I agree with previous answer - you should use base64 approach but using base64 is easy ;). Just use base64 util classes from sun.misc package:

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.IOException;
import java.util.Arrays;
public class Base64Test {

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


    public static void main(String[] args) {
        try {
            String encoded = new BASE64Encoder().encode(tmpIV);
            System.out.println(encoded);
            byte[] decoded = new BASE64Decoder().decodeBuffer(encoded);
            System.out.println(Arrays.equals(tmpIV,decoded));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Karimchik
Don't use classes from non-standard APIs!!
Tom Hawtin - tackline
Indeed. See http://java.sun.com/products/jdk/faq/faq-sun-packages.html
Jon Skeet