简体   繁体   English

在PHP中哈希密码并使用Java进行验证(PASSWORD_BCRYPT和jBcrypt)

[英]Hash password in PHP and verify with Java (PASSWORD_BCRYPT & jBcrypt)

I have a question regarding the hashing of password. 我有一个关于密码哈希的问题。 I am using this on the webpage: 我在网页上使用此:

$pw = password_hash($_POST[password], PASSWORD_BCRYPT);

After that I store this result in the database. 之后,我将结果存储在数据库中。 With my Java Web Service I want to verify the password. 我想使用Java Web Service验证密码。 For that I am using this method: 为此,我正在使用此方法:

   if (BCrypt.checkpw(password, dbPwd)){
       return Response.ok("ok").build();
   }

dbPwd is the one I stored and password is the password in plain text from the first method. dbPwd是我存储的那个,而password是第一种方法的纯文本形式的密码。 Unfortunately I am receiving this error code: 不幸的是,我收到以下错误代码:

javax.servlet.ServletException: java.lang.IllegalArgumentException: Invalid salt revision javax.servlet.ServletException:java.lang.IllegalArgumentException:无效的salt修订版

Update 更新

I found in the internet, that there is a "bug" the Java method is using the 2y and the jBcrypt is using 2a. 我在互联网上发现Java方法使用2y,而jBcrypt使用2a则存在“错误”。 I tried it with 2a and it works, but how can I fix this/ make it work? 我在2a上尝试过,并且可以正常工作,但是如何解决/使其正常工作呢?

After a lot of digging I found a newer implementation of the jBcrypt library: https://github.com/patrickfav/bcrypt 经过大量研究后,我发现了jBcrypt库的较新实现: https : //github.com/patrickfav/bcrypt

I use Scala but the concepts are essentially the same and to verify a $2y$ hash I've created a small utility function: 我使用了Scala,但是概念基本相同,为了验证$2y$哈希,我创建了一个小实用函数:

import at.favre.lib._

  /**
    * Verifies an encrypted password against the expected value
    *
    * @link https://github.com/patrickfav/bcrypt
    * @param hash The hashed password (encypted with BCrypt version $2Y$)
    * @param password The unencrypted password string
    */
  private def verifyBcryptHash(hash: String, password: String): Boolean = {
    if (hash == null || hash.trim.isEmpty)
      false
    else
      BCrypt
        .verifyer()
        .verifyStrict(
          password.toCharArray(),
          hash.toCharArray(),
          BCrypt.Version.VERSION_2Y
        )
        .verified
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM