Go 语言实现 PHP password_hash() 和 password_verify() 函数

package main 

import (
    "fmt"
    "golang.org/x/crypto/bcrypt"
)

func PasswordHash(passwd string) (string, error) {
    bytes, err := bcrypt.GenerateFromPassword([]byte(passwd),12)
    return string(bytes),err
}


func PasswordVerify(passwd,hash string) bool {
    err := bcrypt.CompareHashAndPassword([]byte(hash),[]byte(passwd))
    return err == nil
}

func main() {
    password := "123456"
    hash, _ := PasswordHash(password)

    fmt.Println("密码:",password)
    fmt.Println("hash:",hash)

    match := PasswordVerify(password,hash)
    fmt.Println("验证:",match)
}

输出结果为

密码: 123456
hash: $2a$12$Yg4qpMNaFaHxa44RD7Thle/o4W0bhSBr1YHYLzi/gZOV1wIGl20Vy
验证: true
$2y$$2a$
$2y$$2a$$2y$$2a$