package payment import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "fmt" "io" ) var encryptionKey []byte func InitEncryptionKey(key string) { encryptionKey = []byte(key) } func Encrypt(plaintext string) (string, error) { gcm, err := newGCM() if err != nil { return "", err } nonce := make([]byte, gcm.NonceSize()) if _, err := io.ReadFull(rand.Reader, nonce); err != nil { return "", err } ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil) return base64.StdEncoding.EncodeToString(ciphertext), nil } func Decrypt(encoded string) (string, error) { gcm, err := newGCM() if err != nil { return "", err } ciphertext, err := base64.StdEncoding.DecodeString(encoded) if err != nil { return "", err } nonceSize := gcm.NonceSize() if len(ciphertext) < nonceSize+gcm.Overhead() { return "", fmt.Errorf("ciphertext too short") } nonce := ciphertext[:nonceSize] encrypted := ciphertext[nonceSize:] plaintext, err := gcm.Open(nil, nonce, encrypted, nil) if err != nil { return "", err } return string(plaintext), nil } func newGCM() (cipher.AEAD, error) { if len(encryptionKey) != 32 { return nil, fmt.Errorf("invalid encryption key length: got %d, want 32", len(encryptionKey)) } block, err := aes.NewCipher(encryptionKey) if err != nil { return nil, err } return cipher.NewGCM(block) }