// Package cryptobox is the AES-256-GCM primitive used for everything Vantage // encrypts at rest: SSH private keys, key passphrases, vault secrets, OIDC // client secrets and console credentials. // // It takes a raw key and reads no environment. Key sourcing belongs to the // caller, because the two callers source it differently: the server reads // KEY_ENCRYPTION_KEY at the point of use, while vantagectl is handed one. package cryptobox import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/hex" "fmt" "io" ) // KeySize is the only key length accepted. AES-256 by construction. const KeySize = 32 func gcmFor(key []byte) (cipher.AEAD, error) { if len(key) != KeySize { return nil, fmt.Errorf("key must be %d bytes, got %d", KeySize, len(key)) } block, err := aes.NewCipher(key) if err != nil { return nil, err } return cipher.NewGCM(block) } // Seal encrypts plaintext and returns nonce||ciphertext, hex encoded. func Seal(key []byte, plaintext string) (string, error) { gcm, err := gcmFor(key) if err != nil { return "", err } nonce := make([]byte, gcm.NonceSize()) if _, err := io.ReadFull(rand.Reader, nonce); err != nil { return "", err } return hex.EncodeToString(gcm.Seal(nonce, nonce, []byte(plaintext), nil)), nil } // Open reverses Seal. Every failure mode returns an error that does not // distinguish a wrong key from corrupt data, because the caller cannot act on // the difference and an oracle is worth avoiding for free. func Open(key []byte, ciphertextHex string) (string, error) { gcm, err := gcmFor(key) if err != nil { return "", err } data, err := hex.DecodeString(ciphertextHex) if err != nil { return "", fmt.Errorf("invalid ciphertext encoding") } n := gcm.NonceSize() if len(data) < n { return "", fmt.Errorf("ciphertext too short") } plaintext, err := gcm.Open(nil, data[:n], data[n:], nil) if err != nil { return "", fmt.Errorf("decryption failed") } return string(plaintext), nil }