spring security內(nèi)置加密工具BCryptPasswordEncoder使用不當(dāng)引發(fā)的性能問題

概述

BCrypt的工作因子參數(shù)strength設(shè)置的取值范圍是4-31,如果設(shè)置過高會(huì)導(dǎo)致執(zhí)行效率下降非常明顯。

測(cè)試不同strength耗時(shí)對(duì)比

@Test
    fun testStrengthConfig(){
        // 默認(rèn)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("默認(rèn)strength執(zhí)行耗時(shí):${System.currentTimeMillis() - t1}")

        val t2 = System.currentTimeMillis()
        for (i in 0 until count){
            strength4.encode(pwd)
        }
        println("4 strength執(zhí)行耗時(shí):${System.currentTimeMillis() - t2}")

    }

運(yùn)行結(jié)果

默認(rèn)strength執(zhí)行耗時(shí):6876
4 strength執(zhí)行耗時(shí):110

肉眼可見的性能差別,可見正確設(shè)置strength非常重要。

測(cè)試不同strength加密后的密碼是否能匹配

@Test
    fun match(){
        // 默認(rèn)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))}")
    }

運(yùn)行結(jié)果

1match:true
2match:true
3match:true
4match:true

測(cè)試可見,不同strength加密后的密碼仍舊可以匹配

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容