95 lines
2.1 KiB
Go
95 lines
2.1 KiB
Go
package crypto
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"strings"
|
|
|
|
"golang.org/x/crypto/hkdf"
|
|
)
|
|
|
|
const (
|
|
prefix = "enc:"
|
|
infoLabel = "veola-v1"
|
|
keyLen = 32
|
|
nonceLen = 12
|
|
)
|
|
|
|
// DeriveKey derives a 32-byte AES key from raw key material via HKDF-SHA256.
|
|
func DeriveKey(rawKey []byte) ([]byte, error) {
|
|
if len(rawKey) < 32 {
|
|
return nil, errors.New("raw encryption key must be at least 32 bytes")
|
|
}
|
|
r := hkdf.New(sha256.New, rawKey, nil, []byte(infoLabel))
|
|
out := make([]byte, keyLen)
|
|
if _, err := io.ReadFull(r, out); err != nil {
|
|
return nil, fmt.Errorf("derive key: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func Encrypt(key []byte, plaintext string) (string, error) {
|
|
if plaintext == "" {
|
|
return "", nil
|
|
}
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
nonce := make([]byte, nonceLen)
|
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
|
return "", err
|
|
}
|
|
ct := gcm.Seal(nil, nonce, []byte(plaintext), nil)
|
|
buf := make([]byte, 0, len(nonce)+len(ct))
|
|
buf = append(buf, nonce...)
|
|
buf = append(buf, ct...)
|
|
return prefix + base64.StdEncoding.EncodeToString(buf), nil
|
|
}
|
|
|
|
func Decrypt(key []byte, value string) (string, error) {
|
|
if value == "" {
|
|
return "", nil
|
|
}
|
|
if !IsEncrypted(value) {
|
|
// Plaintext passthrough lets us decrypt rows that pre-date encryption
|
|
// without a separate migration.
|
|
return value, nil
|
|
}
|
|
raw, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(value, prefix))
|
|
if err != nil {
|
|
return "", fmt.Errorf("decode ciphertext: %w", err)
|
|
}
|
|
if len(raw) < nonceLen {
|
|
return "", errors.New("ciphertext too short")
|
|
}
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
nonce, ct := raw[:nonceLen], raw[nonceLen:]
|
|
pt, err := gcm.Open(nil, nonce, ct, nil)
|
|
if err != nil {
|
|
return "", fmt.Errorf("decrypt: %w", err)
|
|
}
|
|
return string(pt), nil
|
|
}
|
|
|
|
func IsEncrypted(value string) bool {
|
|
return strings.HasPrefix(value, prefix)
|
|
}
|