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