crypto.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Package crypto provides cryptographic utilities for password hashing and verification.
  2. package crypto
  3. import (
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "golang.org/x/crypto/bcrypt"
  7. )
  8. // HashPasswordAsBcrypt generates a bcrypt hash of the given password.
  9. func HashPasswordAsBcrypt(password string) (string, error) {
  10. hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  11. return string(hash), err
  12. }
  13. // CheckPasswordHash verifies if the given password matches the bcrypt hash.
  14. func CheckPasswordHash(hash, password string) bool {
  15. return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
  16. }
  17. func IsHashed(s string) bool {
  18. _, err := bcrypt.Cost([]byte(s))
  19. return err == nil
  20. }
  21. // HashTokenSHA256 returns the hex-encoded SHA-256 digest of token. API tokens
  22. // are high-entropy random strings, so a fast unsalted digest is sufficient to
  23. // keep them irrecoverable at rest while allowing constant-time verification.
  24. func HashTokenSHA256(token string) string {
  25. sum := sha256.Sum256([]byte(token))
  26. return hex.EncodeToString(sum[:])
  27. }
  28. // IsSHA256Hex reports whether s looks like a hex-encoded SHA-256 digest
  29. // (64 lowercase hex characters), used to skip already-hashed token rows.
  30. func IsSHA256Hex(s string) bool {
  31. if len(s) != 64 {
  32. return false
  33. }
  34. for _, c := range s {
  35. if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
  36. return false
  37. }
  38. }
  39. return true
  40. }