1 Star 0 Fork 0

后端组 / mvc

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
password.go 2.05 KB
一键复制 编辑 原始数据 按行查看 历史
heweiosc 提交于 2020-04-18 23:32 . add password for components
package components
import "golang.org/x/crypto/bcrypt"
type PasswordStr string
type PasswordByte []byte
var NilPassStr = StrToPassword("")
var NilPassByte = ByteToPassword([]byte(""))
//GeneratePassword 给密码就行加密操作
func Password(userPassword string, cost ...int) (PasswordByte, bool) {
var (
err error
encode []byte
)
if len(cost) == 0 {
cost = append(cost, bcrypt.DefaultCost)
}
if encode, err = bcrypt.GenerateFromPassword([]byte(userPassword), cost[0]); err != nil {
return NilPassByte, false
}
return ByteToPassword(encode), true
}
// 密码比对
func EqualPassword(userPassword string, hashed string) bool {
var err error
if err = bcrypt.CompareHashAndPassword([]byte(hashed), []byte(userPassword)); err != nil {
return false
}
return true
}
func StrToPassword(str string) PasswordStr {
return PasswordStr(str)
}
func ByteToPassword(by []byte) PasswordByte {
return PasswordByte(by)
}
func (b PasswordByte) New(pass []byte, cost ...int) (PasswordByte, bool) {
return Password(string(pass), cost...)
}
func (b PasswordByte) ToString() string {
return string(b)
}
func (b PasswordByte) ToPasswordStr() PasswordStr {
return StrToPassword(b.ToString())
}
func (b PasswordByte) Equals(stPass string) bool {
return EqualPassword(b.ToString(), stPass)
}
func (b PasswordByte) Equal(stPass PasswordByte) bool {
return EqualPassword(b.ToString(), stPass.ToString())
}
func (str PasswordStr) ToString() string {
return string(str)
}
func (str PasswordStr) Equals(stPass string) bool {
return EqualPassword(str.ToString(), stPass)
}
func (str PasswordStr) Equal(stPass PasswordStr) bool {
return EqualPassword(str.ToString(), stPass.ToString())
}
func (str PasswordStr) New(pass string, cost ...int) (PasswordStr, bool) {
if p, ok := Password(pass, cost...); ok {
return p.ToPasswordStr(), ok
}
return NilPassStr, false
}
func (str PasswordStr) ToByte() []byte {
return []byte(str.ToString())
}
func (str PasswordStr) ToPasswordByte() PasswordByte {
return ByteToPassword(str.ToByte())
}
1
https://gitee.com/nuokwan_backend_group/mvc.git
git@gitee.com:nuokwan_backend_group/mvc.git
nuokwan_backend_group
mvc
mvc
1bf86c47ef7b

搜索帮助

53164aa7 5694891 3bd8fe86 5694891