I have a MySQL database where one column is used to store password.
It is implemented in PHP, using password_hash()
to salt and hash the original password on registering, and retrieving the MySQL row of the logging-in user and then password_verify()
its password.
But I need to move it in Java. So are there Java equivalents for password_hash()
and password_verify()
?
You can use the implementation by mindrot:
https://www.mindrot.org/projects/jBCrypt/
To replicate the password_hash
you can use:
String hash = BCrypt.hashpw("password");
And to replicate password_verify
use:
boolean s = BCrypt.checkpw("password", hash);
This works great with my Laravel project.
I made a few tweaks to the lib, to allow the use of a random salt, instead of passing a new one each time you call hashpw
method, and to support multiple versions of salt.
You can find it here: https://github.com/promatik/jBCrypt
Use this: https://mvnrepository.com/artifact/at.favre.lib/bcrypt
Code example:
import at.favre.lib.crypto.bcrypt.*;
import at.favre.lib.bytes.Bytes;
import java.nio.charset.StandardCharsets;
...
String pw = "candidate_password";
String hash = "<hash from users table>";
BCrypt.Result result = BCrypt.verifyer(BCrypt.Version.VERSION_2Y)
.verifyStrict(pw.getBytes(StandardCharsets.UTF_8), hash.getBytes(StandardCharsets.UTF_8));
if (result.verified) {
System.out.println(" It matches");
} else {
System.out.println(" It does not match");
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With