Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

php

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

like image 503
Xenos Avatar asked Apr 07 '16 15:04

Xenos


2 Answers

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

like image 200
António Almeida Avatar answered Oct 24 '22 11:10

António Almeida


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");
            }
...
like image 1
CamelTM Avatar answered Oct 24 '22 09:10

CamelTM