Byte [] to convert an array to a byte array does not work fine in java

I have a byte array initialized as follows:

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, he gives me

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

Then I converted the entire array of bytes to a 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 receive the same data as me. Also in Java, if I convert this string to an array of bytes, I do not get what I 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   
+3
source share
3 answers

The problem is that you converted the byte array to a string in the default encoding of the platform.

(, ,), , - base64.

base64 Java ( AFAIK), , , , Apache Commons Codec.

# - :

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

, , . Java String aString = new String(byteArray) String aString = new String(byteArray, Charset.forName("UTF-8")) (, "UTF-8" )

PS: , , , "-17 -65 -67". , "?" UTF-8

0

I agree with the previous answer - you should use the base64 approach, but using base64 is easy;). Just use the base64 classes from the 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();
        }
    }
}
-4
source

Source: https://habr.com/ru/post/1708787/


All Articles