实际上似乎基准测试设置不正确我已经跟随用户@Luke Joshua Park的resource shared,现在它可以正常工作。
package main
import "testing"
func benchmarkBcrypt(i int, b *testing.B){
for n:= 0; n < b.N; n++ {
HashPassword("my pass", i)
}
}
func BenchmarkBcrypt9(b *testing.B){
benchmarkBcrypt(9, b)
}
func BenchmarkBcrypt10(b *testing.B){
benchmarkBcrypt(10, b)
}
func BenchmarkBcrypt11(b *testing.B){
benchmarkBcrypt(11, b)
}
func BenchmarkBcrypt12(b *testing.B){
benchmarkBcrypt(12, b)
}
func BenchmarkBcrypt13(b *testing.B){
benchmarkBcrypt(13, b)
}
func BenchmarkBcrypt14(b *testing.B){
benchmarkBcrypt(14, b)
}
输出:
BenchmarkBcrypt9-4 30 39543095 ns/op
BenchmarkBcrypt10-4 20 79184657 ns/op
BenchmarkBcrypt11-4 10 158688315 ns/op
BenchmarkBcrypt12-4 5 316070133 ns/op
BenchmarkBcrypt13-4 2 631838101 ns/op
BenchmarkBcrypt14-4 1 1275047344 ns/op
PASS
ok go-playground 10.670s
我在golang的基准测试中有一小部分,我很高兴看到自2018年5月起推荐使用的bcrypt成本。
这是我的基准标记文件:
package main
import "testing"
func BenchmarkBcrypt10(b *testing.B){
HashPassword("my pass", 10)
}
func BenchmarkBcrypt12(b *testing.B){
HashPassword("my pass", 12)
}
func BenchmarkBcrypt13(b *testing.B){
HashPassword("my pass", 13)
}
func BenchmarkBcrypt14(b *testing.B){
HashPassword("my pass", 14)
}
func BenchmarkBcrypt15(b *testing.B){
HashPassword("my pass", 15)
}
这是HashPassword()
内的main.go
func:
import (
"golang.org/x/crypto/bcrypt"
)
func HashPassword(password string, cost int) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), cost)
return string(bytes), err
}
目前的输出是:
go test -bench=.
BenchmarkBcrypt10-4 2000000000 0.04 ns/op
BenchmarkBcrypt12-4 2000000000 0.16 ns/op
BenchmarkBcrypt13-4 2000000000 0.32 ns/op
BenchmarkBcrypt14-4 1 1281338532 ns/op
BenchmarkBcrypt15-4 1 2558998327 ns/op
PASS
对于成本为13的bcrypt来说,花费的时间是0.32纳秒,而成本14的时间是1281338532ns或者~1.2秒 我相信太多了。 2018年当前使用的最佳成本是多少。
答案 0 :(得分:5)
我不确定Benchmark在这里发生了什么。如果您只是计算时间,它可以正常工作,您可以为您找到正确的答案。
package main
import (
"golang.org/x/crypto/bcrypt"
"time"
)
func main() {
cost := 10
start := time.Now()
bcrypt.GenerateFromPassword([]byte("password"), cost)
end := time.Now()
print(end.Sub(start) / time.Millisecond)
}
对于10的工作系数,在我的MacBook Pro上我得到78ms。工作因子11是154ms,12是334ms。所以我们看到正如预期的那样大致翻倍。
目标不是工作因素;这是一个时间。只要你愿意,你就想要。根据我的经验(主要是在客户端应用程序上工作),80-100ms是一个不错的目标,因为与网络请求相比,用户无法检测到,而在暴力攻击方面则是巨大的(因此默认值为10适合我的常用)。
如果我可以提供帮助,我通常会避免在服务器上运行密码扩展,但这种扩展可以在服务器影响和安全性之间进行合理的权衡。请记住,攻击者可能会使用比MacBook Pro快得多的东西,并且可以并行使用多台机器;我选择80-100ms是因为用户体验权衡。 (我可以在客户端上执行密码扩展,然后在服务器上应用SHA-256等廉价哈希。)
但如果你不经常这样做,或者可以花更多的时间在上面,那么更长的当然更好,而在我的MacBook Pro上,14的工作系数大约是1.2秒,我当然会接受一些目的。
但是有一个原因,10仍然是默认值。这不是一个不合理的价值。