Initial commit
This commit is contained in:
94
internal/crypto/crypto.go
Normal file
94
internal/crypto/crypto.go
Normal file
@@ -0,0 +1,94 @@
|
||||
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)
|
||||
}
|
||||
86
internal/crypto/crypto_test.go
Normal file
86
internal/crypto/crypto_test.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func testKey(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
k, err := DeriveKey([]byte("0123456789abcdef0123456789abcdef-aaa"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return k
|
||||
}
|
||||
|
||||
func TestRoundTrip(t *testing.T) {
|
||||
k := testKey(t)
|
||||
cases := []string{
|
||||
"hello",
|
||||
"",
|
||||
"ツインビー グラディウス パロディウス",
|
||||
strings.Repeat("a", 4096),
|
||||
"line1\nline2\ttab",
|
||||
}
|
||||
for _, pt := range cases {
|
||||
ct, err := Encrypt(k, pt)
|
||||
if err != nil {
|
||||
t.Fatalf("encrypt %q: %v", pt, err)
|
||||
}
|
||||
if pt != "" && !IsEncrypted(ct) {
|
||||
t.Errorf("expected enc: prefix on %q", ct)
|
||||
}
|
||||
got, err := Decrypt(k, ct)
|
||||
if err != nil {
|
||||
t.Fatalf("decrypt: %v", err)
|
||||
}
|
||||
if got != pt {
|
||||
t.Errorf("round-trip mismatch: got %q want %q", got, pt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNonceUnique(t *testing.T) {
|
||||
k := testKey(t)
|
||||
a, _ := Encrypt(k, "same plaintext")
|
||||
b, _ := Encrypt(k, "same plaintext")
|
||||
if a == b {
|
||||
t.Error("two encryptions of the same plaintext produced identical ciphertext (nonce not random)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTamperRejected(t *testing.T) {
|
||||
k := testKey(t)
|
||||
ct, _ := Encrypt(k, "secret")
|
||||
tampered := ct[:len(ct)-2] + "AA"
|
||||
if _, err := Decrypt(k, tampered); err == nil {
|
||||
t.Error("expected tampered ciphertext to fail decryption")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrongKeyRejected(t *testing.T) {
|
||||
k1 := testKey(t)
|
||||
k2, _ := DeriveKey([]byte("a-different-32-byte-key-aaaaaaaaaaaa"))
|
||||
ct, _ := Encrypt(k1, "secret")
|
||||
if _, err := Decrypt(k2, ct); err == nil {
|
||||
t.Error("expected decryption with wrong key to fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlaintextPassthrough(t *testing.T) {
|
||||
k := testKey(t)
|
||||
got, err := Decrypt(k, "not-encrypted")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != "not-encrypted" {
|
||||
t.Errorf("plaintext passthrough failed: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeriveKeyRequiresMinLength(t *testing.T) {
|
||||
if _, err := DeriveKey([]byte("too short")); err == nil {
|
||||
t.Error("expected error on short key material")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user