Encryption
The encryption package provides AES-256-GCM encryption and decryption for securing sensitive data. Ciphertext is base64-encoded for safe storage and transport.
Import
import "github.com/gofastadev/gofasta/pkg/encryption"Key Types
Encrypter
type Encrypter struct {
gcm cipher.AEAD
}Key Functions
| Function | Signature | Description |
|---|---|---|
NewEncrypter | func NewEncrypter(key string) (*Encrypter, error) | Creates an AES-256-GCM encrypter with a 32-byte key |
Encrypt | func (e *Encrypter) Encrypt(plaintext string) (string, error) | Encrypts plaintext and returns a base64-encoded ciphertext |
Decrypt | func (e *Encrypter) Decrypt(encoded string) (string, error) | Decrypts a base64-encoded ciphertext back to plaintext |
Usage
AES-256-GCM Encryption and Decryption
enc, err := encryption.NewEncrypter("a-32-byte-secret-key-for-aes256") // must be exactly 32 bytes
if err != nil {
log.Fatalf("failed to create encrypter: %v", err)
}
// Encrypt
ciphertext, err := enc.Encrypt("sensitive data")
if err != nil {
log.Fatalf("encryption failed: %v", err)
}
// Decrypt
plaintext, err := enc.Decrypt(ciphertext)
if err != nil {
log.Fatalf("decryption failed: %v", err)
}
fmt.Println(plaintext) // "sensitive data"Encrypting Structured Data
data, _ := json.Marshal(creditCard)
encrypted, err := enc.Encrypt(string(data))
if err != nil {
return err
}
// Store encrypted string in the databaseConfiguration via config.yaml
encryption:
key: "your-32-byte-secret-key-here!!"Environment variables use the GOFASTA_ prefix (e.g., GOFASTA_ENCRYPTION_KEY).
Note on Password Hashing and HMAC
Password hashing (bcrypt) and HMAC signing are handled in the auth and session packages respectively, not in this package. The encryption package focuses solely on AES-256-GCM symmetric encryption.
Related Pages
Last updated on