AES-GCM Seal And Open With Tamper Rejection
Encrypt and decrypt with AES-GCM from the standard library: a random nonce travels with the ciphertext and one flipped bit fails authentication on open.
Code
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
func seal(key, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key) // key 必须是 16/24/32 字节
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block) // 12 字节 nonce、16 字节认证 tag
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
// Seal 以 nonce 作为 dst 前缀:密文自带 nonce,解密方按长度切出
return gcm.Seal(nonce, nonce, plaintext, nil), nil
}
func open(key, sealed []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
}
if len(sealed) < gcm.NonceSize() {
return nil, fmt.Errorf("ciphertext shorter than nonce")
}
nonce, body := sealed[:gcm.NonceSize()], sealed[gcm.NonceSize():]
// 认证失败时返回 error,绝不输出被篡改的明文
return gcm.Open(nil, nonce, body, nil)
}
func main() {
key := make([]byte, 32) // AES-256:32 字节密钥
if _, err := io.ReadFull(rand.Reader, key); err != nil {
panic(err)
}
sealed, err := seal(key, []byte("transfer 500 cents to acct 7"))
if err != nil {
panic(err)
}
fmt.Printf("sealed %d bytes (nonce %d + body + tag %d)\n",
len(sealed), 12, 16)
plain, err := open(key, sealed)
fmt.Printf("decrypted: %s (err=%v)\n", plain, err)
// 翻转 tag 的一个比特:GCM 认证失败,Open 返回错误而不是错误数据
sealed[len(sealed)-1] ^= 0x01
tampered, err := open(key, sealed)
fmt.Printf("tampered: %q err=%v\n", tampered, err)
}Inside the snippet
AES-GCM Seal And Open With Tamper Rejection keeps everything in the functions seal, open and main.
Error handling is inline: 7 places test err != nil and branch immediately.
What to watch for
- Self-sufficient by design — there is no registry and no lockfile entry.
- No panic path here — failures come back as
errorvalues that each caller must handle.
Using it
The main signature reads func seal(key, plaintext []byte) ([]byte, error)
The demo output is labeled (sealed, decrypted:, tampered:), so each line traces straight back to the statement that printed it.
main calls 2 helpers in sequence: seal and open.
The key statements that remain
return nil, fmt.Errorf("ciphertext shorter than nonce")
if err != nil {
return nil, err
}
if err != nil {
panic(err)
}
Interactive Tools for This Topic
HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
FAQ
- Does the snippet panic on failure?
- As returned `error` values — 7 sites in the snippet check `err` before using other results.
- What does AES-GCM Seal And Open With Tamper Rejection print when run?
- No setup needed: run the file and look for labeled lines like `sealed`, `decrypted:`, `tampered:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.