63 lines
1.3 KiB
Go
63 lines
1.3 KiB
Go
package service
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"errors"
|
|
"io"
|
|
)
|
|
|
|
type AESGCMProtector struct {
|
|
key []byte
|
|
}
|
|
|
|
func NewAESGCMProtectorFromBase64(keyB64 string) (*AESGCMProtector, error) {
|
|
if keyB64 == "" {
|
|
return nil, errors.New("empty key")
|
|
}
|
|
key, err := base64.StdEncoding.DecodeString(keyB64)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(key) != 32 {
|
|
return nil, errors.New("key must be 32 bytes (base64-encoded)")
|
|
}
|
|
return &AESGCMProtector{key: key}, nil
|
|
}
|
|
|
|
func (p *AESGCMProtector) Encrypt(plain []byte) ([]byte, error) {
|
|
block, err := aes.NewCipher(p.key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
nonce := make([]byte, gcm.NonceSize())
|
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
|
return nil, err
|
|
}
|
|
ciphertext := gcm.Seal(nonce, nonce, plain, nil)
|
|
return ciphertext, nil
|
|
}
|
|
|
|
func (p *AESGCMProtector) Decrypt(ciphertext []byte) ([]byte, error) {
|
|
block, err := aes.NewCipher(p.key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(ciphertext) < gcm.NonceSize() {
|
|
return nil, errors.New("ciphertext too short")
|
|
}
|
|
nonce := ciphertext[:gcm.NonceSize()]
|
|
data := ciphertext[gcm.NonceSize():]
|
|
return gcm.Open(nil, nonce, data, nil)
|
|
}
|