How to hash my password in Go, for storing in the mongodb database?

huangapple go评论80阅读模式
英文:

How to hash my password in Go, for storing in the mongodb database?

问题

这是我的/models文件夹,其中包含模式。我应该如何对密码进行哈希处理以存储在MongoDB数据库中?

我使用了Go语言的bcrypt包,但无法实现。

英文:

Here is my /models folder which contains the schema. How hould I hash the password for storing in the mongodb database?

enter image description here

I used the bcrypt package from Go, but was unable to achieve it.

答案1

得分: 2

你需要调用bcrypt.GenerateFromPassword来获取哈希密码:

package password

import "golang.org/x/crypto/bcrypt"

func Hash(password string) (string, error) {
	bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
	return string(bytes), err
}

func Verify(hashed, password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hashed), []byte(password))
	return err == nil
}
英文:

You have to call bcrypt.GenerateFromPassword to get the hashed password:

package password

import "golang.org/x/crypto/bcrypt"

func Hash(password string) (string, error) {
	bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
	return string(bytes), err
}

func Verify(hashed, password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hashed), []byte(password))
	return err == nil
}

huangapple
  • 本文由 发表于 2023年3月17日 00:09:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75758805.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定