8d04b0fde9
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
66 lines
1.4 KiB
Go
66 lines
1.4 KiB
Go
// Package crypto provides AES-256-GCM field encryption keyed from EMCLI_KEY.
|
|
package crypto
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"errors"
|
|
"io"
|
|
"os"
|
|
)
|
|
|
|
var (
|
|
ErrNoKey = errors.New("EMCLI_KEY is not set")
|
|
ErrBadKey = errors.New("EMCLI_KEY must be base64 of exactly 32 bytes")
|
|
)
|
|
|
|
// KeyFromEnv reads and validates the AES-256 key from EMCLI_KEY.
|
|
func KeyFromEnv() ([]byte, error) {
|
|
raw := os.Getenv("EMCLI_KEY")
|
|
if raw == "" {
|
|
return nil, ErrNoKey
|
|
}
|
|
key, err := base64.StdEncoding.DecodeString(raw)
|
|
if err != nil || len(key) != 32 {
|
|
return nil, ErrBadKey
|
|
}
|
|
return key, nil
|
|
}
|
|
|
|
func newGCM(key []byte) (cipher.AEAD, error) {
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return cipher.NewGCM(block)
|
|
}
|
|
|
|
// Seal encrypts plaintext, returning nonce||ciphertext.
|
|
func Seal(key, plaintext []byte) ([]byte, error) {
|
|
gcm, err := newGCM(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
nonce := make([]byte, gcm.NonceSize())
|
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
|
return nil, err
|
|
}
|
|
return gcm.Seal(nonce, nonce, plaintext, nil), nil
|
|
}
|
|
|
|
// Open reverses Seal. A wrong key or tampered blob returns an error.
|
|
func Open(key, blob []byte) ([]byte, error) {
|
|
gcm, err := newGCM(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
ns := gcm.NonceSize()
|
|
if len(blob) < ns {
|
|
return nil, errors.New("ciphertext too short")
|
|
}
|
|
nonce, ct := blob[:ns], blob[ns:]
|
|
return gcm.Open(nil, nonce, ct, nil)
|
|
}
|