You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lib/crypto/password.go

30 lines
652 B
Go

package crypto
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
// EncryptPassword 加密密碼
func EncryptPassword(pwd string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
if err != nil {
return "", fmt.Errorf("failed to encrypt password: %w", err)
}
return string(hash), nil
}
// CheckPassword 檢查密碼
func CheckPassword(pwd, hash string) error {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(pwd))
if err != nil {
// 返回帶有更多上下文信息的錯誤
return fmt.Errorf("password does not match: %w", err)
}
// 如果密碼正確,返回 nil
return nil
}