/! \ I have very little Java knowledge!
SHA256 is not meant for password purposes, for passwords you should use PBDKF2 with SHA256. However you prefer to opt for BCrypt or Argon2i, the PBDKF2 is "ok" but by many is not considered the best.
The difference between BCrypt / PBDKF2 / Argon2i is that they allow you to configure the difficulty, the pure SHA256 is very fast and therefore bad for this purpose. Remember that "human" passwords are often short and limited, since PBDKF2 does iterations that allow you to "take longer" by increasing the cost of brute-force.
The password must be compared in constant-time, this should compare the entire string and not only "die" when a character is different, if this is done it will be exposed to side-channel attacks. Alternatively use bitwise (XOR) comparisons throughout the string, so the processing time will be the same regardless of whether the first bit is different or only the last.
Having said this in Java you can use this implementation , that up to where I analyzed supreme the two questions above, makes bitwise comparisons (via slowEquals()
) and by default has a reasonable number of iterations, which can be changed without breaking the already generated hashes. The other problem is whether the conversion to base64
is safe from cache attacks and if the source of random number generation (for salt
) is secure, this I can not analyze because I do not have knowledge in Java.
This implementation originally used PBDKF2 with SHA-1, but Java8 has support for PBKDF2WithHmacSHA256
, ie SHA256, second to this answer .
Following this implementation of PBKDF2, you use:
String hash = createHash("senha");
Then save it to the database, for example it will result in sha1:64000:18:5Ybc8Ue3EBnLF5Q1eRZj5cUbnH9OGYYG:mTb6Xd35sqw1B9gAcE87vwya
, since it has the salt of 5Ybc8Ue3EBnLF5Q1eRZj5cUbnH9OGYYG and 64000 iterations.
Then do:
verifyPassword("senha", "sha1:64000:18:5Ybc8Ue3EBnLF5Q1eRZj5cUbnH9OGYYG:mTb6Xd35sqw1B9gAcE87vwya")
To verify that the password saved from the database is the same as the password entered.