为什么 bcrypt 库 CompareHashAndPassword 方法很慢?

Why bcrypt library CompareHashAndPassword method is slow?

我想比较密码并使用 bcrypt 库,但是 CompareHashAndPassword 方法非常慢。为什么这个方法很慢?

var b  []byte =  []byte("1234")
 var bx  []byte =  []byte("a$RWV9NhWmlQmSoV9toM/k9OIzaNcYssCiauPVAljiX2NGhqvyxcOMy")
 fmt.Println("Start Compare: ", time.Now().Format("2006-01-02 15:04:05.000000"))
 err := bcrypt.CompareHashAndPassword(bx, b)
 fmt.Println("Completed Compare: ", time.Now().Format("2006-01-02 15:04:05.000000"))
 fmt.Println("------------------------")

结果:

Start Compare: 2018-03-22 22:53:09.142380

Completed Compare: 2018-03-22 22:53:10.347585

你能帮帮我吗?

慢是 bcrypt 的设计特点,因为如果速度快,brute-force 密码哈希就很容易了。来自 Wikipedia:

Besides incorporating a salt to protect against rainbow table attacks, bcrypt is an adaptive function: over time, the iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even with increasing computation power.

在开发和测试时,我降低了 bcrypt 的成本以使 ir 运行 更快

例如:

hashPassword, _ := bcrypt.GenerateFromPassword([]byte(password), 4)
"a$gZUB3tTcsht5JehP3jVxCeOVZSOGzy5ztfXh1kSbp3EDzEXCCH5v."

与我通常的成本值 14

相比,那条线 运行 非常快

那么,当您进行比较时,bcrypt 会读取您的散列成本并进行评估。

在您的示例中,我看到您使用成本 14 来生成该哈希值

[]byte("a$RWV9NhWmlQmSoV9toM/k9OIzaNcYssCiauPVAljiX2NGhqvyxcOMy")

也许降低成本对您也有帮助。