55 lines
1.2 KiB
Go
55 lines
1.2 KiB
Go
package crypto
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"io"
|
|
)
|
|
|
|
// Cipher performs AES-256-GCM encryption of provider secrets.
|
|
type Cipher struct {
|
|
gcm cipher.AEAD
|
|
}
|
|
|
|
func NewCipher(key []byte) (*Cipher, error) {
|
|
if len(key) != 32 {
|
|
return nil, fmt.Errorf("crypto: key must be 32 bytes, got %d", len(key))
|
|
}
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &Cipher{gcm: gcm}, nil
|
|
}
|
|
|
|
// Encrypt returns base64(nonce‖ciphertext).
|
|
func (c *Cipher) Encrypt(plaintext []byte) (string, error) {
|
|
nonce := make([]byte, c.gcm.NonceSize())
|
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
|
return "", err
|
|
}
|
|
sealed := c.gcm.Seal(nonce, nonce, plaintext, nil)
|
|
return base64.StdEncoding.EncodeToString(sealed), nil
|
|
}
|
|
|
|
// Decrypt reverses Encrypt.
|
|
func (c *Cipher) Decrypt(enc string) ([]byte, error) {
|
|
raw, err := base64.StdEncoding.DecodeString(enc)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("crypto: invalid base64: %w", err)
|
|
}
|
|
ns := c.gcm.NonceSize()
|
|
if len(raw) < ns {
|
|
return nil, fmt.Errorf("crypto: ciphertext too short")
|
|
}
|
|
nonce, ct := raw[:ns], raw[ns:]
|
|
return c.gcm.Open(nil, nonce, ct, nil)
|
|
}
|