feat: Extract AES-GCM into shared/cryptobox

services/crypto.go keeps its function names and its KEY_ENCRYPTION_KEY
lookup and delegates the cipher, so vantagectl's verify probe can decrypt
with the same implementation rather than a second copy.
This commit is contained in:
2026-09-07 10:55:54 +00:00
parent 1028a2e43a
commit 577b060b8a
3 changed files with 154 additions and 40 deletions
+8 -40
View File
@@ -1,22 +1,23 @@
package services
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"os"
"gitea.hostxtra.co.uk/mrhid6/vantage/shared/cryptobox"
)
// encryptionKey reads KEY_ENCRYPTION_KEY. The cipher itself lives in
// shared/cryptobox so vantagectl's verify probe uses the same implementation
// rather than a second copy that can drift.
func encryptionKey() ([]byte, error) {
raw := os.Getenv("KEY_ENCRYPTION_KEY")
if raw == "" {
return nil, fmt.Errorf("KEY_ENCRYPTION_KEY is not set")
}
key, err := hex.DecodeString(raw)
if err != nil || len(key) != 32 {
if err != nil || len(key) != cryptobox.KeySize {
return nil, fmt.Errorf("KEY_ENCRYPTION_KEY must be a 64-character hex string (32 bytes)")
}
return key, nil
@@ -27,20 +28,7 @@ func encryptString(plaintext string) (string, error) {
if err != nil {
return "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
sealed := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
return hex.EncodeToString(sealed), nil
return cryptobox.Seal(key, plaintext)
}
func decryptString(ciphertextHex string) (string, error) {
@@ -48,27 +36,7 @@ func decryptString(ciphertextHex string) (string, error) {
if err != nil {
return "", err
}
data, err := hex.DecodeString(ciphertextHex)
if err != nil {
return "", fmt.Errorf("invalid ciphertext encoding")
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonceSize := gcm.NonceSize()
if len(data) < nonceSize {
return "", fmt.Errorf("ciphertext too short")
}
plaintext, err := gcm.Open(nil, data[:nonceSize], data[nonceSize:], nil)
if err != nil {
return "", fmt.Errorf("decryption failed")
}
return string(plaintext), nil
return cryptobox.Open(key, ciphertextHex)
}
func encryptPrivateKey(plaintext string) (string, error) { return encryptString(plaintext) }