[pkg] crypto
使用 bcrypt 來將密碼進行 hashed
Password Hash & Salt Using Golang @ Medium
範例程式碼
password package
// https://github.com/gotify/server/blob/master/auth/password/password.go
// ./password/password.go
package password
import "golang.org/x/crypto/bcrypt"
func CreatePassword(pw string, strength int) []byte {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(pw), strength)
if err != nil {
panic(err)
}
return hashedPassword
}
func ComparePassword(hashedPassword, password []byte) bool {
return bcrypt.CompareHashAndPassword(hashedPassword, password) == nil
}
main
package main
import (
"fmt"
"sandbox/go-sandbox/password"
)
func main() {
ps := "foobar"
hashedPassword := password.CreatePassword(ps, 10)
fmt.Println(hashedPassword)
isSame := password.ComparePassword(hashedPassword, []byte("foobar"))
fmt.Println(isSame) // true
}