7

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

5
  • I don't think there is anything directly compatible (perhaps you could use something from quercus). Commented Apr 7, 2016 at 15:16
  • You could try using this implementation of BCrypt. Commented Apr 7, 2016 at 15:17
  • What algorithm is password_hash using? Commented Apr 7, 2016 at 15:22
  • @BoristheSpider BCRYPT (blowfish) with apparently different cycles count
    – Xenos
    Commented Apr 7, 2016 at 15:28
  • @Xenos you need to work out the number of rounds used, then simply use jBCrypt. Commented Apr 7, 2016 at 15:32

2 Answers 2

6

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

3
  • 1
    Do not forget to add the repo to gradle, i.e. implementation "org.mindrot:jbcrypt:0.4" Commented Oct 8, 2018 at 0:08
  • I have an hash starting with "$2y" and I get java.lang.IllegalArgumentException: Invalid salt revision, do you know why? Thanks
    – Tobia
    Commented Jan 16 at 9:43
  • Finally I found the answer here: stackoverflow.com/questions/49709857/… A string replacement of $2y to $2a is needed
    – Tobia
    Commented Jan 16 at 9:48
1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.