使用 bcrypt 加密后存储密码
2020-04-12 本文已影响0人
星塵子
Go 的 bcrypt
加解密的函数
// 加密明文密码
func GenerateFromPassword(password []byte, cost int) ([]byte, error)
// 密文校验
func CompareHashAndPassword(hashedPassword, password []byte) error
详见文档
使用
package auth
import "golang.org/x/crypto/bcrypt"
//Encrypt 加密明文密码
func Encrypt(password string) (string, error) {
hashedBytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(hashedBytes), err
}
//Compare 密文校验
func Compare(hashedPassword, password string) error {
return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
}
单元测试
package auth
import (
"testing"
"golang.org/x/crypto/bcrypt"
)
func TestCompare(t *testing.T) {
password := "password"
hashedPassword, err := Encrypt(password)
if err != nil {
t.Fatalf("Encrypt error: %s", err)
}
if Compare(hashedPassword, password) != nil {
t.Errorf("%s should hash %s correctly", hashedPassword, password)
}
notPass := "notPass"
if err = Compare(hashedPassword, notPass); err != bcrypt.ErrMismatchedHashAndPassword {
t.Errorf("%s and %s should be mismatched", hashedPassword, notPass)
}
}