Go语言用户密码加密
对密码加密的常规操作是:使用md5+盐+散列。然后将加密结果保存到数据库,但是一般框架底层的加密方式通常会把使用的加密算法和盐值也一起保存到密码中,本文将使用此方式。
1.引入go密码加密包
go get github.com/anaskhan96/go-password-encoder
2.用法
//加密:获取原始密码和选项,返回生成的salt和十六进制编码密码
func Encode(string, *Options) (string, string) {}
//验证:校验密码是否一致,返回true则一致,反之则不一致
func Verify(string, string, string, *Options) bool {}
//Options对象
type Options struct {
SaltLen int //盐的长度,默认256
Iterations int // 函数迭代次数(散列次数),默认10000
KeyLen int // 密钥长度,默认512
HashFunction func() hash.Hash //使用的算法,默认sha512
}
3.示例
import (
"crypto/sha512"
"fmt"
"github.com/anaskhan96/go-password-encoder"
"strings"
)
func main() {
// 使用默认的Options
//salt, encodedPwd := password.Encode("generic password", nil)
//check := password.Verify("generic password", salt, encodedPwd, nil)
//fmt.Println(check) // true
// 自定义options
options := &password.Options{16, 256, 32, sha512.New}
salt, encodedPwd := password.Encode("generic password", options)
//将盐和加密算法放入密码中使用$分割
newPwd := fmt.Sprintf("pbkdf2-sha512$%s$%s",salt,encodedPwd)
//注意newPwd长度,避免数据库截断
fmt.Println(newPwd)
// -------验证------
//从数据库取出密码后应先处理
pwdInfo := strings.Split(newPwd, "$")
fmt.Println(pwdInfo)
// Verify参数:用户输入的密码,盐,数据库存储密码,加密配置参数
check := password.Verify("generic password", pwdInfo[1], pwdInfo[2], options)
fmt.Println(check) // true
}