monorepo/cloud/maplefile-backend/pkg/security/hash/hash.go

45 lines
1.3 KiB
Go

// Package hash provides secure hashing utilities for tokens and sensitive data.
// These utilities are used to hash tokens before storing them as cache keys,
// preventing token leakage through cache key inspection.
package hash
import (
"crypto/sha256"
"encoding/hex"
"github.com/awnumar/memguard"
)
// HashToken creates a SHA-256 hash of a token for use as a cache key.
// This prevents token leakage via cache key inspection.
// The input token bytes are wiped after hashing.
func HashToken(token string) string {
tokenBytes := []byte(token)
defer memguard.WipeBytes(tokenBytes)
hash := sha256.Sum256(tokenBytes)
return hex.EncodeToString(hash[:])
}
// HashBytes creates a SHA-256 hash of byte data.
// If wipeInput is true, the input bytes are wiped after hashing.
func HashBytes(data []byte, wipeInput bool) string {
if wipeInput {
defer memguard.WipeBytes(data)
}
hash := sha256.Sum256(data)
return hex.EncodeToString(hash[:])
}
// HashTokenToBytes creates a SHA-256 hash and returns the raw bytes.
// The input token bytes are wiped after hashing.
func HashTokenToBytes(token string) []byte {
tokenBytes := []byte(token)
defer memguard.WipeBytes(tokenBytes)
hash := sha256.Sum256(tokenBytes)
result := make([]byte, len(hash))
copy(result, hash[:])
return result
}