moataz
moataz

Reputation: 1

Problem when converting bytes [] to string, then back to byte[]

While trying to make a secured connection using AES and RSA I found that when I tried to convert the key to string for sending it over the network, then it converted again to byte[]. The values changed. You can see the code involved below to understand my idea.

public class test {
     public static String asHex (byte buf[]) {
      StringBuffer strbuf = new StringBuffer(buf.length * 2);
      int i;

      for (i = 0; i < buf.length; i++) {
       if (((int) buf[i] & 0xff) < 0x10)
        strbuf.append("0");

       strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
      }

      return strbuf.toString();
     }

 public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException  {


  KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);

SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();

String r = new String(raw,"UTF-8");

System.out.println(asHex(raw));// prints for example fd812245c9bfc4106294d51bf27e3796

byte[] t = r.getBytes("UTF-8");

System.out.println(asHex(t));  // prints for example : efbfbd2245c9bfefbfbd1062efbfbdefbfbd1befbfbd7e37efbfbd

  }
}

Upvotes: 0

Views: 3027

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1499880

When you use the String(byte[], String) constructor, you're saying: "Here is an encoded version of some text, and this is the encoding."

That's not the case here. You don't have encoded text - you have opaque binary data. It's simply not text data. Use Base64 to convert it to a pure-ASCII string safely. There's a public domain Java encoder/decoder you can use.

Upvotes: 4

xappymah
xappymah

Reputation: 1634

It's because of conversion of the raw byte array to UTF-8 String. Since not every byte sequence is a valid UTF-8 string so String constructor can modify it while converting to sort of valid string.

Upvotes: 4

Bozho
Bozho

Reputation: 597036

That's why you should use the hex (or better - base64) representation to transfer byte arrays.

Upvotes: 0

Related Questions