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.
cls/pkg/util/security/password_encoder.go

36 lines
853 B
Go

1 month ago
package security
import (
"golang.org/x/crypto/bcrypt"
"strings"
)
type PasswordEncoder interface {
Encode(rawPassword string) (string, error)
Matches(rawPassword string, encodedPassword string) bool
Prefix() string
}
type BCryptPasswordEncoder struct {
}
var _ PasswordEncoder = (*BCryptPasswordEncoder)(nil)
func (b *BCryptPasswordEncoder) Encode(rawPassword string) (string, error) {
encodePw, err := bcrypt.GenerateFromPassword([]byte(rawPassword), bcrypt.DefaultCost)
if err != nil {
return "", err
} else {
return b.Prefix() + string(encodePw), nil
}
}
func (b *BCryptPasswordEncoder) Matches(rawPassword, passWd string) bool {
raw := strings.TrimPrefix(rawPassword, b.Prefix())
return bcrypt.CompareHashAndPassword([]byte(raw), []byte(passWd)) == nil
}
func (b *BCryptPasswordEncoder) Prefix() string {
return "{bcrypt}"
}