Files
2026-09-03 08:36:04 +05:30

67 lines
1.5 KiB
Go

// Package secrets encrypts connection credentials (API tokens, passwords)
// at rest using AES-256-GCM, keyed from the application secret.
package secrets
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"io"
)
type Box struct {
gcm cipher.AEAD
}
// New derives an AES-256 key from the application secret via SHA-256.
func New(secret string) (*Box, error) {
if secret == "" {
return nil, errors.New("secrets: app secret must not be empty")
}
key := sha256.Sum256([]byte(secret))
block, err := aes.NewCipher(key[:])
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
return &Box{gcm: gcm}, nil
}
func (b *Box) Encrypt(plaintext string) (string, error) {
if plaintext == "" {
return "", nil
}
nonce := make([]byte, b.gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
ciphertext := b.gcm.Seal(nonce, nonce, []byte(plaintext), nil)
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
func (b *Box) Decrypt(encoded string) (string, error) {
if encoded == "" {
return "", nil
}
data, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return "", err
}
nonceSize := b.gcm.NonceSize()
if len(data) < nonceSize {
return "", errors.New("secrets: ciphertext too short")
}
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
plaintext, err := b.gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", err
}
return string(plaintext), nil
}