Standard library / crypto/cipher
crypto/cipher.AEAD
Authenticated encryption with associated data. NonceSize and Overhead describe required nonce and tag overhead; Seal appends ciphertext and tag to dst; Open verifies and decrypts, rejecting changed ciphertext or associated data. Nonce must be unique for each encryption under a key; never trust output on failure (dst storage may be overwritten). Use random nonces within a per-key bound or a managed unique counter. Example uses fresh ephemeral key and random nonce; only prints verified plaintext. Expected stdout: 'Go\n'.
Formal Syntax & Structure
go syntaxgo
type AEAD interface { NonceSize() int
Overhead() int
Seal(dst, nonce, plaintext, additionalData []byte) []byte
Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)}Working Example
Example Snippetgo
package main
import ( "crypto/aes" "crypto/cipher" "crypto/rand" "fmt")
func main() { key := make([]byte, 32) _, err := rand.Read(key) check(err) var g cipher.AEAD = must(cipher.NewGCM(must(aes.NewCipher(key)))) n := make([]byte, g.NonceSize()) _, err = rand.Read(n) check(err) sealed := g.Seal(nil, n, []byte("Go"), []byte("v1")) plain := must(g.Open(nil, n, sealed, []byte("v1"))) fmt.Println(string(plain))}func must[T any](v T, e error) T { if e != nil { panic(e) } return v}func check(e error) { if e != nil { panic(e) }}