Golang实现php的两个函数password_hash和password_verify

xiaohai 2019-12-31 17:41:28 4770人围观 标签: Go 
简介Golang实现php的两个函数password_hash和password_verify

转载地址:Golang实现php的两个函数password_hash和password_verify

利用golang.org/x/crypto/bcrypt 包里面实现,使用前请先 go get 安装此包。对用户的密码进行hash处理,可以用下面两个函数实现。

package main

import (
	"fmt"
	"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
}

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

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

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

执行结果:

go run test.go 密码: 123456 hash: $2a$10$kEsTv4h971dtZpXToGCFPO/Fb6K/IypI79LmUxXbw0T7Qy/fflt/K 验证: true