Xenos
Xenos

Reputation: 3507

What's the Java equivalent for PHP's password_hash and password_verify?

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()?

Upvotes: 7

Views: 6613

Answers (2)

CamelTM
CamelTM

Reputation: 1250

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");
            }
...

Upvotes: 1

Ant&#243;nio Almeida
Ant&#243;nio Almeida

Reputation: 10117

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

Upvotes: 6

Related Questions