How to Encrypt Data with AES in Go (GCM Mode)

Encrypt data in Go using AES-GCM by creating a cipher from a key and sealing plaintext with a random nonce.

Use the crypto/cipher package to create an AES-GCM cipher and call Seal to encrypt data with a nonce.

package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
)

func encrypt(key, plaintext []byte) ([]byte, error) {
	block, err := aes.NewCipher(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 := rand.Read(nonce); err != nil {
		return nil, err
	}
	return gcm.Seal(nonce, nonce, plaintext, nil), nil
}