I've been looking around and the closest answer is : How to generate a random alpha-numeric string?
I want to follow this workflow according to this CrackStation tutorial:
To Store a Password
Generate a long random salt using a CSPRNG.
Prepend the salt to the password and hash it with a standard cryptographic hash function such as SHA256.
Save both the salt and the hash in the user's database record.
To Validate a Password
Retrieve the user's salt and hash from the database.
Prepend the salt to the given password and hash it using the same hash function.
Compare the hash of the given password with the hash from the database. If they match, the password is correct. Otherwise, the password is incorrect.
I don't know how to generate a SALT. I figured out how to generate a hash using the MessageDigest. I tried using SecureRandom but nextByte method produces garbled code.
Edit: I don't know which answer to choose, they're too complicated for me, I have decided to use jBCrypt; jBCript is easy to use, does all the complex stuff behind the scenes. so I'll let the community vote up for the best answer.
You were right regarding how you want to generate salt i.e. its nothing but a random number. For this particular case it would protect your system from possible Dictionary attacks. Now, for the second problem what you could do is instead of using UTF-8 encoding you may want to use Base64. Here, is a sample for generating a hash. I am using Apache Common Codecs for doing the base64 encoding you may select one of your own
Here is some additional reference of the standard practice in password hashing directly from OWASP
Here's my solution, i would love anyone's opinion on this, it's simple for beginners
You can validate by just decoding the
strSalt
and using the samehash
method:Another version using SHA-3, I am using bouncycastle:
The interface:
The implementation:
The test cases:
pom.xml (only dependencies):
Inspired from this post and that post, I use this code to generate and verify hashed salted passwords. It only uses JDK provided classes, no external dependency.
The process is:
getNextSalt
hash
method to generate a salted and hashed password. The method returns abyte[]
which you can save as is in a database with the saltisExpectedPassword
method to check that the details match