Files

69 lines
1.3 KiB
Go

package services
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
type CryptoService struct {
gcm cipher.AEAD
}
func NewCryptoService(rawKey string) (*CryptoService, error) {
key := []byte(rawKey)
if len(key) < 32 {
padded := make([]byte, 32)
copy(padded, key)
key = padded
}
if len(key) > 32 {
key = key[:32]
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
return &CryptoService{gcm: gcm}, nil
}
func (c *CryptoService) Encrypt(plain string) (string, error) {
nonce := make([]byte, c.gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
ciphertext := c.gcm.Seal(nonce, nonce, []byte(plain), nil)
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
func (c *CryptoService) Decrypt(token string) (string, error) {
raw, err := base64.StdEncoding.DecodeString(token)
if err != nil {
return "", err
}
nonceSize := c.gcm.NonceSize()
if len(raw) < nonceSize {
return "", fmt.Errorf("ciphertext too short")
}
nonce, ciphertext := raw[:nonceSize], raw[nonceSize:]
plain, err := c.gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", err
}
return string(plain), nil
}