Documentation ¶
Overview ¶
Package cryptutil provides cryptographic utility functions, complementing the lower level abstractions found in the standard library.
Index ¶
- Constants
- Variables
- func CertificateFromBase64(cert, key string) (*tls.Certificate, error)
- func CertificateFromFile(certFile, keyFile string) (*tls.Certificate, error)
- func CheckHMAC(data, suppliedMAC, key []byte) bool
- func CheckPasswordHash(hash, password []byte) error
- func DecodePrivateKey(encodedKey []byte) (*ecdsa.PrivateKey, error)
- func DecodePublicKey(encodedKey []byte) (*ecdsa.PublicKey, error)
- func Decrypt(a cipher.AEAD, data, ad []byte) ([]byte, error)
- func EncodeCertificate(cert *tls.Certificate) (pemCertificateBytes, pemKeyBytes []byte, err error)
- func EncodePrivateKey(key *ecdsa.PrivateKey) ([]byte, error)
- func EncodePublicKey(key *ecdsa.PublicKey) ([]byte, error)
- func Encrypt(a cipher.AEAD, data, ad []byte) []byte
- func GenerateCertificate(sharedKey []byte, domain string, configure ...func(*x509.Certificate)) (*tls.Certificate, error)
- func GenerateHMAC(data, key []byte) []byte
- func GetCertPool(ca, caFile string) (*x509.CertPool, error)
- func GetCertificateServerNames(cert *tls.Certificate) []string
- func GetKeyEncryptionKeyID(raw []byte) string
- func HasCertificateForServerName(certificates []tls.Certificate, serverName string) bool
- func Hash(tag string, data []byte) []byte
- func HashPassword(password []byte) ([]byte, error)
- func HashProto(msg proto.Message) []byte
- func MarshalPKCS8PrivateKey(key any) ([]byte, error)
- func MarshalPKIXPublicKey(pub any) ([]byte, error)
- func MatchesServerName(cert *tls.Certificate, serverName string) bool
- func NewAEADCipher(secret []byte) (cipher.AEAD, error)
- func NewAEADCipherFromBase64(s string) (cipher.AEAD, error)
- func NewBase64Key() string
- func NewKey() []byte
- func NewRandomStringN(c int) string
- func NewRandomUInt32() uint32
- func NewRandomUInt64() uint64
- func NewSigningKey() (*ecdsa.PrivateKey, error)
- func ParseCRLs(crl []byte) (map[string]*x509.RevocationList, error)
- func ParsePEMCertificate(raw []byte) (*x509.Certificate, error)
- func ParsePEMCertificateFromBase64(encoded string) (*x509.Certificate, error)
- func ParsePEMCertificateFromFile(file string) (*x509.Certificate, error)
- func ParsePKCS8PrivateKey(der []byte) (any, error)
- func ParsePKIXPublicKey(derBytes []byte) (pub any, err error)
- func PrivateJWKFromBytes(data []byte) (*jose.JSONWebKey, error)
- func PrivateJWKsFromBytes(data []byte) ([]*jose.JSONWebKey, error)
- func Pseudonymize(key []byte, data string) string
- func PublicJWKFromBytes(data []byte) (*jose.JSONWebKey, error)
- func PublicJWKsFromBytes(data []byte) ([]*jose.JSONWebKey, error)
- func SignatureAlgorithmForKey(key any) (jose.SignatureAlgorithm, error)
- func ValidTimestamp(ts string) error
- type CertificatesIndex
- type DataEncryptionKey
- func (dek *DataEncryptionKey) Decrypt(ciphertext []byte) ([]byte, error)
- func (dek *DataEncryptionKey) DecryptString(ciphertext string) (string, error)
- func (dek *DataEncryptionKey) Encrypt(plaintext []byte) []byte
- func (dek *DataEncryptionKey) EncryptString(plaintext string) string
- func (dek *DataEncryptionKey) KeyBytes() []byte
- type DataEncryptionKeyCache
- type KeyEncryptionKey
- type KeyEncryptionKeySource
- type KeyEncryptionKeySourceFunc
- type PrivateKeyEncryptionKey
- func (kek *PrivateKeyEncryptionKey) Decrypt(ciphertext []byte) ([]byte, error)
- func (kek *PrivateKeyEncryptionKey) DecryptDataEncryptionKey(ciphertext []byte) (*DataEncryptionKey, error)
- func (kek *PrivateKeyEncryptionKey) ID() string
- func (kek *PrivateKeyEncryptionKey) KeyBytes() []byte
- func (kek *PrivateKeyEncryptionKey) Public() *PublicKeyEncryptionKey
- type PublicKeyEncryptionKey
- type SecretToken
- type SecureToken
- func (secureToken SecureToken) Bytes() []byte
- func (secureToken SecureToken) Expiry() time.Time
- func (secureToken SecureToken) HMAC() [SecureTokenHMACLength]byte
- func (secureToken SecureToken) String() string
- func (secureToken SecureToken) Token() Token
- func (secureToken SecureToken) Verify(key []byte, now time.Time) error
- type Token
Examples ¶
Constants ¶
const ( // DataEncryptionKeySize is the size of a data encryption key. DataEncryptionKeySize = chacha20poly1305.KeySize // DataEncryptionKeyCacheSize is the number of DEKs to keep in the LRU cache. DataEncryptionKeyCacheSize = 20 )
const ( // SecureTokenTimeLength is the length of the time part of the SecureToken. SecureTokenTimeLength = 8 // SecureTokenHMACLength is the length of the HMAC part of the SecureToken. SecureTokenHMACLength = 32 // SecureTokenLength is the byte length of a SecureToken. SecureTokenLength = TokenLength + SecureTokenTimeLength + SecureTokenHMACLength )
const DefaultKeySize = 32
DefaultKeySize is the default key size in bytes.
const ( // DefaultLeeway defines the default leeway for matching NotBefore/Expiry claims. DefaultLeeway = 5.0 * time.Minute )
const KeyEncryptionKeySize = curve25519.ScalarSize
KeyEncryptionKeySize is the size of a key encryption key.
const TokenLength = 16
TokenLength is the length of a token.
Variables ¶
var ( ErrExpired = errors.New("expired") ErrInvalid = errors.New("invalid") )
errors related to the SecureToken
Functions ¶
func CertificateFromBase64 ¶
func CertificateFromBase64(cert, key string) (*tls.Certificate, error)
CertificateFromBase64 returns an X509 pair from a base64 encoded blob.
func CertificateFromFile ¶
func CertificateFromFile(certFile, keyFile string) (*tls.Certificate, error)
CertificateFromFile given a certificate, and key file path, returns a X509 keypair.
func CheckHMAC ¶
CheckHMAC securely checks the supplied MAC against a message using the shared secret key.
func CheckPasswordHash ¶
CheckPasswordHash securely compares a bcrypt hashed password with its possible plaintext equivalent. Returns nil on success, or an error on failure.
func DecodePrivateKey ¶
func DecodePrivateKey(encodedKey []byte) (*ecdsa.PrivateKey, error)
DecodePrivateKey decodes a PEM-encoded ECDSA private key.
func DecodePublicKey ¶
DecodePublicKey decodes a PEM-encoded ECDSA public key.
func EncodeCertificate ¶ added in v0.19.0
func EncodeCertificate(cert *tls.Certificate) (pemCertificateBytes, pemKeyBytes []byte, err error)
EncodeCertificate encodes a TLS certificate into PEM compatible byte slices. Returns `nil`, `nil` if there is an error marshaling the PKCS8 private key.
func EncodePrivateKey ¶
func EncodePrivateKey(key *ecdsa.PrivateKey) ([]byte, error)
EncodePrivateKey encodes an ECDSA private key to PEM format.
func EncodePublicKey ¶
EncodePublicKey encodes an ECDSA public key to PEM format.
func Encrypt ¶
Encrypt encrypts a value with optional associated data
Panics if source of randomness fails.
func GenerateCertificate ¶ added in v0.22.0
func GenerateCertificate(sharedKey []byte, domain string, configure ...func(*x509.Certificate)) (*tls.Certificate, error)
GenerateCertificate generates a TLS certificate derived from a shared key.
func GenerateHMAC ¶
GenerateHMAC produces a symmetric signature using a shared secret key.
func GetCertPool ¶ added in v0.11.0
GetCertPool gets a cert pool for the given CA or CAFile.
func GetCertificateServerNames ¶ added in v0.21.0
func GetCertificateServerNames(cert *tls.Certificate) []string
GetCertificateServerNames gets all the certificate's server names. Will return an empty slice if certificate is nil, empty, or x509 parsing fails.
func GetKeyEncryptionKeyID ¶ added in v0.14.0
GetKeyEncryptionKeyID derives an id from the key encryption key data itself.
func HasCertificateForServerName ¶ added in v0.21.0
func HasCertificateForServerName(certificates []tls.Certificate, serverName string) bool
HasCertificateForServerName returns true if a TLS certificate matches the given server name.
func Hash ¶
Hash generates a hash of data using HMAC-SHA-512/256. The tag is intended to be a natural-language string describing the purpose of the hash, such as "hash file for lookup key" or "master secret to client secret". It serves as an HMAC "key" and ensures that different purposes will have different hash output. This function is NOT suitable for hashing passwords.
Example ¶
tag := "hashing file for lookup key" contents, err := os.ReadFile("testdata/random") if err != nil { fmt.Printf("could not read file: %v\n", err) os.Exit(1) } digest := Hash(tag, contents) fmt.Println(hex.EncodeToString(digest))
Output: 9f4c795d8ae5c207f19184ccebee6a606c1fdfe509c793614066d613580f03e1
func HashPassword ¶
HashPassword generates a bcrypt hash of the password using work factor 14.
func HashProto ¶ added in v0.12.0
HashProto hashes a protobuf message. It sets `Deterministic` to true to ensure the encoded message is always the same. (ie map order is lexographic)
func MarshalPKCS8PrivateKey ¶ added in v0.14.0
MarshalPKCS8PrivateKey wraps x509.MarshalPKCS8PrivateKey with added support for KeyEncryptionKeys.
func MarshalPKIXPublicKey ¶ added in v0.14.0
MarshalPKIXPublicKey wraps x509.MarshalPKIXPublicKey with added support for KeyEncryptionKeys.
func MatchesServerName ¶ added in v0.21.0
func MatchesServerName(cert *tls.Certificate, serverName string) bool
MatchesServerName returns true if the certificate matches the server name.
func NewAEADCipher ¶
NewAEADCipher takes secret key and returns a new XChacha20poly1305 cipher.
func NewAEADCipherFromBase64 ¶
NewAEADCipherFromBase64 takes a base64 encoded secret key and returns a new XChacha20poly1305 cipher.
func NewBase64Key ¶
func NewBase64Key() string
NewBase64Key generates a random base64 encoded 32-byte key.
Panics if source of randomness fails.
func NewKey ¶
func NewKey() []byte
NewKey generates a random 32-byte (256 bit) key.
Panics if source of randomness fails.
func NewRandomStringN ¶
NewRandomStringN returns base64 encoded random string of a given num of bytes.
Panics if source of randomness fails.
func NewRandomUInt32 ¶ added in v0.18.0
func NewRandomUInt32() uint32
NewRandomUInt32 returns a random uint32.
Panics if source of randomness fails.
func NewRandomUInt64 ¶ added in v0.14.0
func NewRandomUInt64() uint64
NewRandomUInt64 returns a random uint64.
Panics if source of randomness fails.
func NewSigningKey ¶
func NewSigningKey() (*ecdsa.PrivateKey, error)
NewSigningKey generates a random P-256 ECDSA private key. Go's P-256 is constant-time (which prevents certain types of attacks) while its P-384 and P-521 are not.
func ParseCRLs ¶ added in v0.23.0
func ParseCRLs(crl []byte) (map[string]*x509.RevocationList, error)
ParseCRLs parses PEM-encoded certificate revocation lists, returning a map of the parsed CRLs keyed by the raw issuer name.
func ParsePEMCertificate ¶ added in v0.15.0
func ParsePEMCertificate(raw []byte) (*x509.Certificate, error)
ParsePEMCertificate parses a PEM encoded certificate block.
func ParsePEMCertificateFromBase64 ¶ added in v0.17.4
func ParsePEMCertificateFromBase64(encoded string) (*x509.Certificate, error)
ParsePEMCertificateFromBase64 parses a PEM encoded certificate block from a base64 encoded string.
func ParsePEMCertificateFromFile ¶ added in v0.15.0
func ParsePEMCertificateFromFile(file string) (*x509.Certificate, error)
ParsePEMCertificateFromFile decodes a PEM certificate from a file.
func ParsePKCS8PrivateKey ¶ added in v0.14.0
ParsePKCS8PrivateKey wraps x509.ParsePKCS8PrivateKey with added support for KeyEncryptionKeys.
func ParsePKIXPublicKey ¶ added in v0.14.0
ParsePKIXPublicKey wraps x509.ParsePKIXPublicKey with added support for KeyEncryptionKeys.
func PrivateJWKFromBytes ¶
PrivateJWKFromBytes returns a jose JSON Web _Private_ Key from bytes.
func PrivateJWKsFromBytes ¶ added in v0.21.0
PrivateJWKsFromBytes returns jose JSON Web _Private_ Keys from bytes.
func Pseudonymize ¶ added in v0.27.2
Pseudonymize pseudonymizes data by computing the HMAC-SHA256 of the data.
func PublicJWKFromBytes ¶
PublicJWKFromBytes returns a jose JSON Web _Public_ Key from bytes.
func PublicJWKsFromBytes ¶ added in v0.21.0
PublicJWKsFromBytes returns jose JSON Web _Public_ Keys from bytes.
func SignatureAlgorithmForKey ¶ added in v0.15.6
SignatureAlgorithmForKey returns the signature algorithm for the given key.
func ValidTimestamp ¶
ValidTimestamp is a helper function often used in conjunction with an HMAC function to verify that the timestamp (in unix seconds) is within leeway period.
Types ¶
type CertificatesIndex ¶ added in v0.22.3
type CertificatesIndex struct {
// contains filtered or unexported fields
}
A CertificatesIndex indexes certificates to determine if there is overlap between them.
func NewCertificatesIndex ¶ added in v0.22.3
func NewCertificatesIndex() *CertificatesIndex
NewCertificatesIndex creates a new CertificatesIndex.
func (*CertificatesIndex) Add ¶ added in v0.22.3
func (c *CertificatesIndex) Add(cert *x509.Certificate)
Add adds a certificate to the index.
func (*CertificatesIndex) OverlapsWithExistingCertificate ¶ added in v0.22.3
func (c *CertificatesIndex) OverlapsWithExistingCertificate(cert *x509.Certificate) (bool, string)
OverlapsWithExistingCertificate returns true if the certificate overlaps with an existing certificate.
type DataEncryptionKey ¶ added in v0.14.0
type DataEncryptionKey struct {
// contains filtered or unexported fields
}
A DataEncryptionKey is an XChaCha20Poly1305 symmetric encryption key. For more details see the documentation on KeyEncryptionKeys.
func GenerateDataEncryptionKey ¶ added in v0.14.0
func GenerateDataEncryptionKey() (*DataEncryptionKey, error)
GenerateDataEncryptionKey generates a new random data encryption key.
func NewDataEncryptionKey ¶ added in v0.14.0
func NewDataEncryptionKey(raw []byte) (*DataEncryptionKey, error)
NewDataEncryptionKey returns a new DataEncryptionKey from existing bytes.
func (*DataEncryptionKey) Decrypt ¶ added in v0.14.0
func (dek *DataEncryptionKey) Decrypt(ciphertext []byte) ([]byte, error)
Decrypt decrypts encrypted data using the data encryption key.
func (*DataEncryptionKey) DecryptString ¶ added in v0.14.0
func (dek *DataEncryptionKey) DecryptString(ciphertext string) (string, error)
DecryptString decrypts an encrypted string using the data encryption key and base64 encoding.
func (*DataEncryptionKey) Encrypt ¶ added in v0.14.0
func (dek *DataEncryptionKey) Encrypt(plaintext []byte) []byte
Encrypt encrypts data using the data encryption key.
func (*DataEncryptionKey) EncryptString ¶ added in v0.14.0
func (dek *DataEncryptionKey) EncryptString(plaintext string) string
EncryptString encrypts a string using the data encryption key and base64 encoding.
func (*DataEncryptionKey) KeyBytes ¶ added in v0.14.0
func (dek *DataEncryptionKey) KeyBytes() []byte
KeyBytes returns the private key encryption key's raw bytes.
type DataEncryptionKeyCache ¶ added in v0.14.0
type DataEncryptionKeyCache struct {
// contains filtered or unexported fields
}
A DataEncryptionKeyCache caches recently used data encryption keys based on their encrypted representation. The cache is safe for concurrent read and write access.
Internally an LRU cache is used and the encrypted DEK bytes are converted to strings to allow usage as hash map keys.
func NewDataEncryptionKeyCache ¶ added in v0.14.0
func NewDataEncryptionKeyCache() *DataEncryptionKeyCache
NewDataEncryptionKeyCache creates a new DataEncryptionKeyCache.
func (*DataEncryptionKeyCache) Get ¶ added in v0.14.0
func (cache *DataEncryptionKeyCache) Get(encryptedDEK []byte) (*DataEncryptionKey, bool)
Get returns a data encryption key if available.
func (*DataEncryptionKeyCache) Put ¶ added in v0.14.0
func (cache *DataEncryptionKeyCache) Put(encryptedDEK []byte, dek *DataEncryptionKey)
Put stores a data encryption key by its encrypted representation.
type KeyEncryptionKey ¶ added in v0.14.0
type KeyEncryptionKey interface { ID() string KeyBytes() []byte // contains filtered or unexported methods }
A KeyEncryptionKey (KEK) is used to implement *envelope encryption*, similar to how data is stored at rest with AWS or Google Cloud:
- AWS: https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#enveloping
- Google Cloud: https://cloud.google.com/kms/docs/envelope-encryption
Data is encrypted with a data encryption key (DEK) and that key is stored next to the data encrypted with the KEK. Finally the KEK id is also stored with the data.
To decrypt the data you first retrieve the KEK, second decrypt the DEK, and finally decrypt the data using the DEK.
- Our KEKs are asymmetric Curve25519 keys. We use the *public* key to encrypt the DEK so only the *private* key can decrypt it.
- Our DEKs are symmetric XChaCha20Poly1305 keys.
type KeyEncryptionKeySource ¶ added in v0.14.0
type KeyEncryptionKeySource interface {
GetKeyEncryptionKey(id string) (*PrivateKeyEncryptionKey, error)
}
A KeyEncryptionKeySource gets private key encryption keys based on their id.
type KeyEncryptionKeySourceFunc ¶ added in v0.14.0
type KeyEncryptionKeySourceFunc func(id string) (*PrivateKeyEncryptionKey, error)
A KeyEncryptionKeySourceFunc implements the KeyEncryptionKeySource interface using a function.
func (KeyEncryptionKeySourceFunc) GetKeyEncryptionKey ¶ added in v0.14.0
func (src KeyEncryptionKeySourceFunc) GetKeyEncryptionKey(id string) (*PrivateKeyEncryptionKey, error)
GetKeyEncryptionKey gets the key encryption key by calling the underlying function.
type PrivateKeyEncryptionKey ¶ added in v0.14.0
type PrivateKeyEncryptionKey struct {
// contains filtered or unexported fields
}
PrivateKeyEncryptionKey is a Curve25519 asymmetric private encryption key used to decrypt data encryption keys.
func GenerateKeyEncryptionKey ¶ added in v0.14.0
func GenerateKeyEncryptionKey() (*PrivateKeyEncryptionKey, error)
GenerateKeyEncryptionKey generates a new random key encryption key.
func NewPrivateKeyEncryptionKey ¶ added in v0.14.0
func NewPrivateKeyEncryptionKey(raw []byte) (*PrivateKeyEncryptionKey, error)
NewPrivateKeyEncryptionKey creates a new encryption key from existing bytes.
func (*PrivateKeyEncryptionKey) Decrypt ¶ added in v0.14.0
func (kek *PrivateKeyEncryptionKey) Decrypt(ciphertext []byte) ([]byte, error)
Decrypt decrypts data from a NACL anonymous box.
func (*PrivateKeyEncryptionKey) DecryptDataEncryptionKey ¶ added in v0.14.0
func (kek *PrivateKeyEncryptionKey) DecryptDataEncryptionKey(ciphertext []byte) (*DataEncryptionKey, error)
DecryptDataEncryptionKey decrypts a data encryption key.
func (*PrivateKeyEncryptionKey) ID ¶ added in v0.14.0
func (kek *PrivateKeyEncryptionKey) ID() string
ID returns the private key's id.
func (*PrivateKeyEncryptionKey) KeyBytes ¶ added in v0.14.0
func (kek *PrivateKeyEncryptionKey) KeyBytes() []byte
KeyBytes returns the private key encryption key's raw bytes.
func (*PrivateKeyEncryptionKey) Public ¶ added in v0.14.0
func (kek *PrivateKeyEncryptionKey) Public() *PublicKeyEncryptionKey
Public returns the private key's public key.
type PublicKeyEncryptionKey ¶ added in v0.14.0
type PublicKeyEncryptionKey struct {
// contains filtered or unexported fields
}
PublicKeyEncryptionKey is a Curve25519 asymmetric public encryption key used to encrypt data encryption keys.
func NewPublicKeyEncryptionKey ¶ added in v0.14.0
func NewPublicKeyEncryptionKey(raw []byte) (*PublicKeyEncryptionKey, error)
NewPublicKeyEncryptionKey creates a new encryption key from existing bytes.
func NewPublicKeyEncryptionKeyWithID ¶ added in v0.14.0
func NewPublicKeyEncryptionKeyWithID(id string, raw []byte) (*PublicKeyEncryptionKey, error)
NewPublicKeyEncryptionKeyWithID creates a new encryption key from an existing id and bytes.
func (*PublicKeyEncryptionKey) Encrypt ¶ added in v0.14.0
func (kek *PublicKeyEncryptionKey) Encrypt(plaintext []byte) ([]byte, error)
Encrypt encrypts data using a NACL anonymous box.
func (*PublicKeyEncryptionKey) EncryptDataEncryptionKey ¶ added in v0.14.0
func (kek *PublicKeyEncryptionKey) EncryptDataEncryptionKey(dek *DataEncryptionKey) ([]byte, error)
EncryptDataEncryptionKey encrypts a DataEncryptionKey.
func (*PublicKeyEncryptionKey) ID ¶ added in v0.14.0
func (kek *PublicKeyEncryptionKey) ID() string
ID returns the public key's id.
func (*PublicKeyEncryptionKey) KeyBytes ¶ added in v0.14.0
func (kek *PublicKeyEncryptionKey) KeyBytes() []byte
KeyBytes returns the public key's raw bytes.
type SecretToken ¶
A SecretToken is made up of an id and a secret.
func SecretTokenFromString ¶
func SecretTokenFromString(rawstr string) (tok SecretToken, ok bool)
SecretTokenFromString parses a base58-encoded string into a secret token.
func (SecretToken) String ¶
func (tok SecretToken) String() string
String returns the SecretToken as a base58-encoded string.
type SecureToken ¶ added in v0.15.6
type SecureToken [SecureTokenLength]byte
A SecureToken is an HMAC'd Token with an expiration time.
func GenerateSecureToken ¶ added in v0.15.6
func GenerateSecureToken(key []byte, expiry time.Time, token Token) SecureToken
GenerateSecureToken generates a SecureToken from the given key, expiry and token.
func SecureTokenFromString ¶ added in v0.15.6
func SecureTokenFromString(rawstr string) (secureToken SecureToken, ok bool)
SecureTokenFromString parses a base58-encoded string into a SecureToken.
func (SecureToken) Bytes ¶ added in v0.15.6
func (secureToken SecureToken) Bytes() []byte
Bytes returns the secret token as bytes.
func (SecureToken) Expiry ¶ added in v0.15.6
func (secureToken SecureToken) Expiry() time.Time
Expiry returns the SecureToken expiration time.
func (SecureToken) HMAC ¶ added in v0.15.6
func (secureToken SecureToken) HMAC() [SecureTokenHMACLength]byte
HMAC returns the HMAC part of the SecureToken.
func (SecureToken) String ¶ added in v0.15.6
func (secureToken SecureToken) String() string
String returns the SecureToken as a string.
func (SecureToken) Token ¶ added in v0.15.6
func (secureToken SecureToken) Token() Token
Token returns the Token part of the SecureToken.
type Token ¶
type Token [TokenLength]byte
A Token is a globally unique identifier.
func NewRandomToken ¶
func NewRandomToken() (tok Token)
NewRandomToken returns a new random Token (via a random UUID).
func TokenFromString ¶
TokenFromString parses a base58-encoded string into a token.