Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

byte to string and vice versa

I need to convert a salt value randomly generated and store it in the database. To store it in the database I converted it to a string. Then for retrieving the original value, I convert it back to byte. But both value are not matching. I have tried "UTF-8","UTF-16", BASE64Encoder.

SecureRandom ranGen = new SecureRandom();
byte[] aesKey = new byte[16]; // 16 bytes = 128 bits
ranGen.nextBytes(aesKey);   
System.out.println(aesKey);

String a=new String(aesKey,"UTF-16");
byte[] b=new byte[16];
b=a.getBytes("UTF-16");
System.out.println(b);

Outputs for the above code(Executed it 2 times):

[B@11563ff
[B@1581593

and

[B@170888e
[B@11563ff
like image 800
Ashwin Avatar asked Jan 17 '23 11:01

Ashwin


2 Answers

You really ought to use Base64 for converting binary data to Strings. There are lots of free implementations available, for example the one found in Apache Commons Codec.

Also, it's really easy to use, for example:

For encoding:

import org.apache.commons.codec.binary.Base64;
...
byte[] abValue = {...}; // Your data to encode
Base64 base64 = new Base64();
String strEncodedData = base64.encodeToString(abValue).trim();

For decoding:

import org.apache.commons.codec.binary.Base64;
...
String strEncodedData = "..."; // Your previously encoded data
Base64 base64 = new Base64();
byte[] abValue = base64.decode(strValue);
like image 135
Sirs Avatar answered Jan 20 '23 01:01

Sirs


As your code is written above, printing aesKey and then b, what you are actually printing is the output of the toString method for an array object, which is just the default Object toString method. So I don't see how you can expect them to be the same.

If you really want to check they are the same you should compare them byte by byte.

In terms of your actual question regarding storing a byte[] as a String in the DB, your best bet is to Base64 encode it. I would suggest using the Apache Commons Codec library for this. See the user guide.

EDIT:

Using the BASE64Encode and BASE64Decoder you have referred to, the code would be like this:

    SecureRandom ranGen = new SecureRandom();
    byte[] aesKey = new byte[16]; // 16 bytes = 128 bits
    ranGen.nextBytes(aesKey);
    String a = new BASE64Encoder().encode(aesKey);

    System.out.println(a);

    byte[] b = new BASE64Decoder().decodeBuffer(a);
    System.out.println(new BASE64Encoder().encode(b));

    for (int i = 0; i < aesKey.length; i++) {
        System.out.println(aesKey[i] + " " + b[i]);
    }

Here, I have also looped through the bytes individually, to show that they are indeed equal.

like image 29
DaveJohnston Avatar answered Jan 20 '23 01:01

DaveJohnston