Files
AI-Expert-Sidebar/internal/crypto/crypto.go
T
2026-04-01 14:09:33 +08:00

66 lines
1.5 KiB
Go

package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
)
const appSecret = "ai-expert-sidebar-v1-local-©2026"
// deriveKey produces a 32-byte AES key from the application secret.
func deriveKey() []byte {
sum := sha256.Sum256([]byte(appSecret))
return sum[:]
}
// EncryptAPIKey encrypts a plaintext API key. Returns "" for empty input.
func EncryptAPIKey(plaintext string) (string, error) {
if plaintext == "" {
return "", nil
}
block, err := aes.NewCipher(deriveKey())
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 base64.StdEncoding.EncodeToString(sealed), nil
}
// DecryptAPIKey decrypts a base64-encoded AES-256-GCM ciphertext. Returns "" for empty input.
func DecryptAPIKey(ciphertext64 string) (string, error) {
if ciphertext64 == "" {
return "", nil
}
data, err := base64.StdEncoding.DecodeString(ciphertext64)
if err != nil {
return "", fmt.Errorf("base64 decode: %w", err)
}
block, err := aes.NewCipher(deriveKey())
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
ns := gcm.NonceSize()
if len(data) < ns {
return "", fmt.Errorf("ciphertext too short")
}
plain, err := gcm.Open(nil, data[:ns], data[ns:], nil)
return string(plain), err
}