0

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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.