Golang使用bcrypt實(shí)現(xiàn)密碼加密和校驗(yàn)的操作代碼
bcrypt可以用于數(shù)據(jù)庫中的用戶密碼保存,相比md5而言更加的安全可靠
文檔
https://pkg.go.dev/golang.org/x/crypto/bcrypt
文檔上給出了標(biāo)準(zhǔn)文檔,這個(gè)庫是下面這個(gè)文件描述的算法golang實(shí)現(xiàn):
https://www.usenix.org/legacy/event/usenix99/provos/provos.pdf
安裝
go get -u golang.org/x/crypto/bcrypt
加密示例
package main import ( "fmt" "golang.org/x/crypto/bcrypt" ) func main() { password := "123456" hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) fmt.Println(string(hashedPassword)) // $2a$10$EvdBpymvP7uDfI0TFRD6RO3YXLwQWUVYKMDqbWFloYCtyNXHCmbD2 // $2a$10$6JDH6z7dJljoDo4VolpHbeIgzqHwhUvF1JRJ/h7Ibf/PjGtx.wZGG }
可以看到,多次運(yùn)行后,生成的結(jié)果是不一樣的
bcrypt不能解密,不過可以比較加密后的數(shù)據(jù)和加密前的數(shù)據(jù)是否相匹配
package main import ( "fmt" "golang.org/x/crypto/bcrypt" ) func main() { password := "123456" hashedPassword := "$2a$10$EvdBpymvP7uDfI0TFRD6RO3YXLwQWUVYKMDqbWFloYCtyNXHCmbD2" err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) fmt.Println(err) // <nil> }
由于算法的入?yún)⒑统鰠⒍际亲止?jié)類型的數(shù)據(jù),為了便于使用,可以將兩個(gè)方法簡單封裝成一個(gè)工具類,將入?yún)⒑统鰠⒍几臑槭亲址愋偷臄?shù)據(jù)
package utils import ( "golang.org/x/crypto/bcrypt" ) func GenerateFromPassword(password string) (string, error) { hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { return "", err } return string(hashedPassword), err } func CompareHashAndPassword(hashPassword string, password string) bool { err := bcrypt.CompareHashAndPassword([]byte(hashPassword), []byte(password)) return err == nil }
到此這篇關(guān)于Golang使用bcrypt實(shí)現(xiàn)密碼加密和校驗(yàn)的文章就介紹到這了,更多相關(guān)Golang密碼加密和校驗(yàn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Golang?動(dòng)態(tài)腳本調(diào)研詳解
這篇文章主要為大家介紹了Golang?動(dòng)態(tài)腳本調(diào)研詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09golang 實(shí)現(xiàn)struct、json、map互相轉(zhuǎn)化
這篇文章主要介紹了golang 實(shí)現(xiàn)struct、json、map互相轉(zhuǎn)化,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-12-12GoLang實(shí)現(xiàn)Viper庫的封裝流程詳解
Viper是一個(gè)用于Go語言應(yīng)用程序的配置管理庫,它提供了一種簡單而靈活的方式來處理應(yīng)用程序的配置,支持多種格式的配置文件,這篇文章主要介紹了GoLang封裝Viper庫的流程,感興趣的同學(xué)可以參考下文2023-05-05淺析go語言如何實(shí)現(xiàn)協(xié)程的搶占式調(diào)度的
go語言通過GMP模型實(shí)現(xiàn)協(xié)程并發(fā),為了避免單協(xié)程持續(xù)持有線程導(dǎo)致線程隊(duì)列中的其他協(xié)程饑餓問題,設(shè)計(jì)者提出了一個(gè)搶占式調(diào)度機(jī)制,本文會(huì)基于一個(gè)簡單的代碼示例對(duì)搶占式調(diào)度過程進(jìn)行深入講解剖析2024-04-04