35 lines
720 B
Go
35 lines
720 B
Go
package auth
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
const bcryptCost = 12
|
|
|
|
func HashPassword(password string) (string, error) {
|
|
if strings.TrimSpace(password) == "" {
|
|
return "", fmt.Errorf("password is required")
|
|
}
|
|
|
|
if len(password) > 72 {
|
|
return "", fmt.Errorf("password must be 72 bytes or fewer")
|
|
}
|
|
|
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
|
|
if err != nil {
|
|
return "", fmt.Errorf("hash password: %w", err)
|
|
}
|
|
|
|
return string(hashedPassword), nil
|
|
}
|
|
|
|
func ComparePassword(hash, password string) error {
|
|
if hash == "" {
|
|
return fmt.Errorf("password hash is required")
|
|
}
|
|
|
|
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
|
}
|