Go实现password_hash和password_verify

Golang 投稿 60100 0 评论

Go实现password_hash和password_verify

先 go get 安装 golang.org/x/crypto/bcrypt 包来实现。

对用户的密码进行hash处理,可以用下面两个函数实现。

package main
 
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
 
func PasswordHash(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(bytes), err
}
 
func PasswordVerify(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
 
func main() {
password := "feishuai.vip"
hash, _ := PasswordHash(password)
 
fmt.Println("密码:", password)
fmt.Println("hash:", hash)
 
match := PasswordVerify(password, hash)
fmt.Println("验证:", match)
}

编程笔记 » Go实现password_hash和password_verify

赞同 (69) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽