[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 HashPassword(password string) (string, error) {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 10)
if err != nil {
return "", err
}
return string(hashedPassword), nil
}
func CompareHash(hashedPassword, password string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
return err == nil
}
main
package main
import (
"fmt"
"sandbox/go-sandbox/password"
)
func main() {
ps := "foobar"
hashedPassword, _ := Hash(ps)
isSame := CompareHash(hashedPassword, "foobar")
fmt.Println(isSame) // true
}