30 lines
652 B
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: %v", 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: %v", err)
|
|
}
|
|
|
|
// 如果密碼正確,返回 nil
|
|
return nil
|
|
}
|