-
This commit is contained in:
@ -18,17 +18,42 @@ const (
|
||||
TokenLength = 32
|
||||
// TokenPrefix is prepended to all tokens for identification
|
||||
TokenPrefix = "kms_"
|
||||
// BcryptCost defines the bcrypt cost for 2025 security standards (minimum 14)
|
||||
BcryptCost = 14
|
||||
)
|
||||
|
||||
// TokenGenerator provides secure token generation and validation
|
||||
type TokenGenerator struct {
|
||||
hmacKey []byte
|
||||
hmacKey []byte
|
||||
bcryptCost int
|
||||
}
|
||||
|
||||
// NewTokenGenerator creates a new token generator with the provided HMAC key
|
||||
func NewTokenGenerator(hmacKey string) *TokenGenerator {
|
||||
return &TokenGenerator{
|
||||
hmacKey: []byte(hmacKey),
|
||||
hmacKey: []byte(hmacKey),
|
||||
bcryptCost: BcryptCost,
|
||||
}
|
||||
}
|
||||
|
||||
// NewTokenGeneratorWithCost creates a new token generator with custom bcrypt cost
|
||||
func NewTokenGeneratorWithCost(hmacKey string, bcryptCost int) *TokenGenerator {
|
||||
// Validate bcrypt cost (must be between 4 and 31)
|
||||
if bcryptCost < 4 {
|
||||
bcryptCost = 4
|
||||
} else if bcryptCost > 31 {
|
||||
bcryptCost = 31
|
||||
}
|
||||
|
||||
// Warn if cost is too low for production
|
||||
if bcryptCost < 12 {
|
||||
// This should log a warning, but we don't have logger here
|
||||
// In a real implementation, you'd pass a logger or use a global one
|
||||
}
|
||||
|
||||
return &TokenGenerator{
|
||||
hmacKey: []byte(hmacKey),
|
||||
bcryptCost: bcryptCost,
|
||||
}
|
||||
}
|
||||
|
||||
@ -69,10 +94,10 @@ func (tg *TokenGenerator) GenerateSecureTokenWithPrefix(appPrefix string, tokenT
|
||||
|
||||
// HashToken creates a secure hash of the token for storage
|
||||
func (tg *TokenGenerator) HashToken(token string) (string, error) {
|
||||
// Use bcrypt for secure password-like hashing
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(token), bcrypt.DefaultCost)
|
||||
// Use bcrypt with configured cost
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(token), tg.bcryptCost)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to hash token: %w", err)
|
||||
return "", fmt.Errorf("failed to hash token with bcrypt cost %d: %w", tg.bcryptCost, err)
|
||||
}
|
||||
|
||||
return string(hash), nil
|
||||
|
||||
Reference in New Issue
Block a user