go php password_hash 加解密实现
注意: 下面的演示需要放到go模块中才能运行 因为有依赖go的内部包bcrypt
# 模块化项目更新
go mod tiny
main.go
import (
"fmt"
"encoding/base64"
"utils"
)
func main() {
cipher, err := utils.PasswordHash("admin")
if err != nil {
panic(err)
}
fmt.Println("加密后的密文:" + cipher)
isOk := utils.PasswordVerify("admin", cipher)
fmt.Println(fmt.Sprintf("验证结果: %v", isOk))
bs64Cipher := base64.StdEncoding.EncodeToString([]byte(cipher))
fmt.Println("Base64编码后的字符: " + bs64Cipher)
cipherDcodeBs, _ := base64.StdEncoding.DecodeString(bs64Cipher)
fmt.Println(fmt.Sprintf("验证结果: %v", utils.PasswordVerify("admin", string(cipherDcodeBs))))
}
utils.go
package utils
import (
"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
}
|