first commit

This commit is contained in:
2024-07-23 10:23:43 +08:00
commit 7b4c2521a3
126 changed files with 15931 additions and 0 deletions

39
pkg/bcrypt/password.go Normal file
View File

@ -0,0 +1,39 @@
package bcrypt
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
var _ Password = (*password)(nil)
type Password interface {
i()
Generate(pwd string) string
Validate(pwd, hash string) bool
}
type password struct {
cost int
}
func (p *password) i() {}
func NewPassword(cost int) (Password, error) {
if cost < bcrypt.MinCost || cost > bcrypt.MaxCost {
return nil, fmt.Errorf("cost out of range")
}
return &password{
cost: cost,
}, nil
}
func (p *password) Generate(pwd string) string {
hash, _ := bcrypt.GenerateFromPassword([]byte(pwd), p.cost)
return string(hash)
}
func (p *password) Validate(pwd, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(pwd))
return err == nil
}