package apikey import ( "crypto/sha256" "crypto/subtle" "encoding/base64" ) // Hasher hashes and verifies API keys using SHA-256 type Hasher interface { // Hash creates a deterministic SHA-256 hash of the API key Hash(apiKey string) string // Verify checks if the API key matches the hash using constant-time comparison Verify(apiKey string, hash string) bool } type hasher struct{} // NewHasher creates a new API key hasher func NewHasher() Hasher { return &hasher{} } // Hash creates a deterministic SHA-256 hash of the API key func (h *hasher) Hash(apiKey string) string { hash := sha256.Sum256([]byte(apiKey)) return base64.StdEncoding.EncodeToString(hash[:]) } // Verify checks if the API key matches the hash using constant-time comparison // This prevents timing attacks func (h *hasher) Verify(apiKey string, expectedHash string) bool { actualHash := h.Hash(apiKey) return subtle.ConstantTimeCompare([]byte(actualHash), []byte(expectedHash)) == 1 }