英文:
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?
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论