Below is a simple example of how to perform AES‐GCM (symmetric) encryption and decryption in Go. This is one of the most common—and secure—patterns for encrypting data at rest or in transit.
go
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"fmt"
"io"
)
// encryptAESGCM encrypts plaintext using AES-GCM.
// It returns the ciphertext (with nonce prepended) or an error.
func encryptAESGCM(key, plaintext []byte) ([]byte, error) {
// 1) Create an AES block from the key.
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// 2) Wrap it in GCM
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
// 3) Create a nonce. GCM standard nonce size is 12 bytes.
nonce := make([]byte, aesgcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
// 4) Seal appends the encrypted data to nonce and returns the result.
ciphertext := aesgcm.Seal(nonce, nonce, plaintext, nil)
return ciphertext, nil
}
// decryptAESGCM decrypts data produced by encryptAESGCM.
func decryptAESGCM(key, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := aesgcm.NonceSize()
if len(ciphertext) < nonceSize {
return nil, errors.New("ciphertext too short")
}
// 1) Extract nonce and actual ciphertext
nonce, ct := ciphertext[:nonceSize], ciphertext[nonceSize:]
// 2) Open will decrypt and authenticate.
plaintext, err := aesgcm.Open(nil, nonce, ct, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}
func main() {
// 1) Choose a 16-, 24- or 32-byte key (AES-128, AES-192, AES-256).
key := []byte("a very secret key!!") // 16 bytes
message := []byte("Hello, Go encryption! 🎉")
fmt.Printf("Original: %s\n", message)
// 2) Encrypt
encrypted, err := encryptAESGCM(key, message)
if err != nil {
panic(err)
}
fmt.Printf("Encrypted (base64): %x\n", encrypted)
// 3) Decrypt
decrypted, err := decryptAESGCM(key, encrypted)
if err != nil {
panic(err)
}
fmt.Printf("Decrypted: %s\n", decrypted)
}
How it works step by step:
Key selection
– Must be 16/24/32 bytes for AES-128/192/256.
NewCipher
– aes.NewCipher(key) initializes the block cipher.
GCM wrapper
– cipher.NewGCM(block) turns AES into an authenticated stream.
Nonce (IV)
– Generate 12 random bytes (aesgcm.NonceSize()). Must be unique per encryption.
Seal
– Combines nonce + ciphertext + authentication tag.
Open
– Verifies tag, decrypts, returns plaintext.
Remember:
Never reuse a nonce with the same key!
Store or transmit the nonce alongside ciphertext (we prepended it).
Keep your key secret.
— — —
If you need asymmetric encryption (e.g. RSA), Go’s crypto/rsa package can help. Let me know if you’d like an RSA example too!