salt created by Java SecureRandom has different getBytes() value

1.2k views Asked by At

I use java SecureRandom to create salt to encrypt user. However, when I tried to match user with salt and password, they failed on different machine. The user is created on a Linux test machine and I copy the database down to my OS X machine. The match succeeded on the test machine but failed on my OS X.

Same salt get different bytes with the following code, even the length are different:

salt.getBytes()

enter image description here

enter image description here

And here is the salt generation process:

        SecureRandom random = new SecureRandom();
        byte bytes[] = new byte[20];
        random.nextBytes(bytes);
        String salt = new String(bytes);
        user.setSalt(salt);

Is is possible that getBytes() may have different value for the same salt on different machine?

2

There are 2 answers

3
assylias On BEST ANSWER

Don't do that: String salt = new String(bytes);

You are transforming a series of bytes into a string using the default encoding of the machine. You should keep the byte array as a byte array.

If you store the data in a database you can store it in a binary string column (bytea in postgresql for example - may be blob in other DBs).

1
gawi On

According to String.getBytes():

getBytes() Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

Therefore if you have different charset on the machines result will be different.