go php password_hash 加解密实现
注意: 下面的演示需要放到go模块中才能运行 因为有依赖go的内部包bcrypt
# 模块化项目更新go mod tiny
main.go
import ("fmt""encoding/base64""utils")func main() {// go php password_hash加解密实现示例// password_hash 加密cipher, err := utils.PasswordHash("admin")if err != nil {panic(err)}fmt.Println("加密后的密文:" + cipher) //这个密文同一个密码每次都不一样//验证密码isOk := utils.PasswordVerify("admin", cipher)fmt.Println(fmt.Sprintf("验证结果: %v", isOk))//为了方便观看这里base64加密一下 取出对比是需要解密// base64加密bs64Cipher := base64.StdEncoding.EncodeToString([]byte(cipher))fmt.Println("Base64编码后的字符: " + bs64Cipher)// base64解密cipherDcodeBs, _ := base64.StdEncoding.DecodeString(bs64Cipher)fmt.Println(fmt.Sprintf("验证结果: %v", utils.PasswordVerify("admin", string(cipherDcodeBs))))/** //输出结果:加密后的密文:$2a$10$BJWO/I6WJ04m/zQMTIr5P.gvcd9.LoWjYFgz/tnfaliuDdeEennUG验证结果: trueBase64编码后的字符: JDJhJDEwJEJKV08vSTZXSjA0bS96UU1USXI1UC5ndmNkOS5Mb1dqWUZnei90bmZhbGl1RGRlRWVublVH验证结果: true*/}
utils.go
package utilsimport ("/x/crypto/bcrypt")// PasswordHash php的函数password_hashfunc PasswordHash(password string) (string, error) {bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)return string(bytes), err}// PasswordVerify php的函数password_verifyfunc PasswordVerify(password, hash string) bool {err := pareHashAndPassword([]byte(hash), []byte(password))return err == nil}