概述
BCrypt的工作因子参数strength设置的取值范围是4-31,如果设置过高会导致执行效率下降非常明显。
测试不同strength耗时对比
@Test
fun testStrengthConfig(){
// 默认strength
val strengthDefault = BCryptPasswordEncoder()
// 4 strength
val strength4 = BCryptPasswordEncoder(4)
val pwd = "123456"
val count = 100
val t1 = System.currentTimeMillis()
for (i in 0 until count){
strengthDefault.encode(pwd)
}
println("默认strength执行耗时:${System.currentTimeMillis() - t1}")
val t2 = System.currentTimeMillis()
for (i in 0 until count){
strength4.encode(pwd)
}
println("4 strength执行耗时:${System.currentTimeMillis() - t2}")
}
运行结果
默认strength执行耗时:6876
4 strength执行耗时:110
肉眼可见的性能差别,可见正确设置strength非常重要。
测试不同strength加密后的密码是否能匹配
@Test
fun match(){
// 默认strength
val strengthDefault = BCryptPasswordEncoder()
// 4 strength
val strength4 = BCryptPasswordEncoder(4)
val pwd = "sdfd@#$@#sdfsdf"
println("1match:${strengthDefault.matches(pwd, strength4.encode(pwd))}")
println("2match:${strength4.matches(pwd, strengthDefault.encode(pwd))}")
println("3match:${strengthDefault.matches(pwd, strengthDefault.encode(pwd))}")
println("4match:${strength4.matches(pwd, strength4.encode(pwd))}")
}
运行结果
1match:true
2match:true
3match:true
4match:true
测试可见,不同strength加密后的密码仍旧可以匹配