Reputation: 27496
If I do something like
int keyLength = 160; // because SHA1 generates 160-bit hashes
int iterations = 20 * 1000; //standard is 2000 but let's be more secure here
KeySpec spec = new PBEKeySpec(password.toCharArray(), generateSalt(), iterations, keyLength);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] hash = keyFactory.generateSecret(spec).getEncoded();
How do I convert this hash into String so it can be saved into DB?I tried new String(hash, "UTF-8");
but that gives malformed characters like l��0\�w�c��Q�
.
Upvotes: 0
Views: 610
Reputation: 51711
If you'll always consume your key as a byte[]
in your application it would be far better to save it as a BLOB binary object itself in the database. You'll save yourself from conversion errors.
Upvotes: 1
Reputation: 18148
You need to encode the byte array into a Base64 string, then decode it back to a byte array when you read it from the database. Note that the encoded string will be around 33% larger than the original byte array.
Upvotes: 5