代码地址:https://gitcode.net/m0_51510236/go_password
首先我们来初始化一个项目
go mod init go_password
golang密码加密我们可以使用 golang.org/x/crypto/bcrypt
包:
go get "golang.org/x/crypto/bcrypt"
然后我们可以在 utils
包中编写一个 password.go
文件,用于密码加密,代码如下:
package utils
import "golang.org/x/crypto/bcrypt"
func EncryptPassword(password string) (string, error) {
encryptPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
} else {
return string(encryptPassword), nil
}
}
func EqualsPassword(password, encryptPassword string) bool {
err := bcrypt.CompareHashAndPassword([]byte(encryptPassword), []byte(password))
return err == nil
}
然后我们编写一个程序执行一下这个加密代码:
package main
import (
"fmt"
"go_password/utils"
)
func main() {
password := "123456"
encrypt1, _ := utils.EncryptPassword(password)
fmt.Printf("第一次加密密码:%v\n", encrypt1)
encrypt2, _ := utils.EncryptPassword(password)
fmt.Printf("第一次加密密码:%v\n", encrypt2)
passwordEquals := utils.EqualsPassword(password, encrypt1)
fmt.Printf("使用第一次加密的密码字符串对比密码是否正确:%v\n", passwordEquals)
passwordEquals = utils.EqualsPassword(password, encrypt2)
fmt.Printf("使用第二次加密的密码字符串对比密码是否正确:%v\n", passwordEquals)
passwordEquals = utils.EqualsPassword("1234567", encrypt1)
fmt.Printf("尝试用错误的密码对比密码是否正确:%v\n", passwordEquals)
}
运行这个 main
方法,我们可以查看结果:
我们可以看到两次密码加密的结果是不一样的,因为对密码加密的时候添加了盐。这种密码加密是非常安全且不可逆的,可以放心使用,并且我们对比密码是否正确也返回了正确的结果,可以用这个方法去写一个注册登陆的功能了!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)