0

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?

Ryan Zhu
  • 543
  • 3
  • 9
  • 20

2 Answers2

1

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.

gawi
  • 2,843
  • 4
  • 29
  • 44
1

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).

assylias
  • 321,522
  • 82
  • 660
  • 783
  • I see, so, if I don't want to change the salt data type, can I just give a charset, like 'utf-8' as the second parameter to the `new String(bytes,'utf-8') to workaround? – Ryan Zhu Jun 17 '15 at 09:17
  • @RyanZhu Not all series of bytes can be encoded into a valid UTF_8 string so that won't work either. Your salt isn't a string so there is no reason to put it in a string... Try this for example: `byte[] b = {-128}; byte[] b2 = new String(b, UTF_8).getBytes(UTF_8); System.out.println(Arrays.toString(b2));` – assylias Jun 17 '15 at 09:21
  • See also the duplicate question I just posted and this: http://stackoverflow.com/questions/16853957/convert-byte-salt-to-string-in-java – assylias Jun 17 '15 at 09:24