Skip to content

Instantly share code, notes, and snippets.

@x893675
Created September 3, 2020 07:49
Show Gist options
  • Save x893675/f50bd36daf34a6e608e5bebcccbc862a to your computer and use it in GitHub Desktop.
Save x893675/f50bd36daf34a6e608e5bebcccbc862a to your computer and use it in GitHub Desktop.
store password by bcrypt
package main
import (
"golang.org/x/crypto/bcrypt"
"log"
)
// bcrypt主要由四部分组成
// Prefix说明了使用的bcrypt的版本
// Cost是进行哈希的次数-数字越大生成bcrypt的速度越慢,成本越大。同样也意味着如果密码库被盗,攻击者想通过暴力破解的方法猜测出用户密码的成本变得越昂贵。
// Salt是添加到要进行哈希的字符串中的随机字符(21.25个字符),所以使用bcrypt时不需要我们在表里单独存储Salt。
// Hashed Text是明文字符串最终被bcrypt应用这些设置哈希后的哈希文本
func main() {
passwordOK := "admin"
passwordERR := "password"
hash, err := bcrypt.GenerateFromPassword([]byte(passwordOK), bcrypt.DefaultCost)
if err != nil {
log.Fatal(err)
}
encodePW := string(hash)
log.Println(encodePW)
err = bcrypt.CompareHashAndPassword([]byte(encodePW), []byte(passwordOK))
if err != nil {
log.Println("password wrong")
} else {
log.Println("password ok")
}
err = bcrypt.CompareHashAndPassword([]byte(encodePW), []byte(passwordERR))
if err != nil {
log.Println("password wrong")
} else {
log.Println("password ok")
}
c, err := bcrypt.Cost([]byte(encodePW))
if err != nil {
log.Fatal(err)
}
if c != bcrypt.DefaultCost {
log.Printf("expected cost is %d, bug got %d", bcrypt.DefaultCost, c)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment