AES CTR Stream Cipher Roundtrip
Turn a block cipher into a stream with cipher.NewCTR: one keystream per direction, XORKeyStream both ways, and why an IV must never repeat under the same key.
Code
package main
import (
"crypto/aes"
"crypto/cipher"
"fmt"
)
func main() {
// 演示用固定密钥;生产环境用 crypto/rand 生成
key := make([]byte, 32)
for i := range key {
key[i] = byte(i)
}
// CTR 的 IV 与分组等长(aes.BlockSize):相同密钥下绝不复用,
// 否则两段密文共享同一条 keystream,等于泄露明文的异或
iv := make([]byte, aes.BlockSize)
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
// cipher.Stream:CTR 把分组密码变成流密码,XORKeyStream 就是加解密本体
stream := cipher.NewCTR(block, iv)
plaintext := []byte("wire transfer: 42 to acct 7")
ciphertext := make([]byte, len(plaintext))
stream.XORKeyStream(ciphertext, plaintext)
fmt.Printf("ciphertext: %x\n", ciphertext)
// 往返 roundtrip:解密方向重建同一条 keystream。
// Stream 内部有状态,每个方向各建一份,不能复用已消耗的 stream
decrypt := cipher.NewCTR(block, iv)
recovered := make([]byte, len(ciphertext))
decrypt.XORKeyStream(recovered, ciphertext)
fmt.Println("recovered:", string(recovered))
// 换 IV 即换 keystream:密文随之改变
iv2 := make([]byte, aes.BlockSize)
iv2[0] = 1
other := make([]byte, len(plaintext))
cipher.NewCTR(block, iv2).XORKeyStream(other, plaintext)
fmt.Printf("same key new iv: %x\n", other)
// 注意:CTR 只保证机密性、没有完整性校验;要防篡改用 GCM 或外加 HMAC
}Watching the execution
AES CTR Stream Cipher Roundtrip keeps everything in the function main.
One loop does the cycling here: for i := range key. Every err != nil branch (1 site) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.
What to watch for
- Free of dependencies by construction — no registry, no lockfile lines.
- Failures abort via
panic(err)— nothing is returned for the caller to check, and nothing in the snippet recovers.
Using it
The entry-point signature is func main()
The demo output is labeled (ciphertext:, recovered:, same key new iv:); each label names the call that printed it.
Key statements
for i := range key {
key[i] = byte(i)
}
if err != nil {
panic(err)
}
ciphertext := make([]byte, len(plaintext))
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
- How are errors reported?
- By aborting: each of the 1 `err != nil` branches calls `panic(err)`, so a failure stops the program at the point it is detected.
- What does AES CTR Stream Cipher Roundtrip print when run?
- Running the file directly is enough — expect labeled output lines such as `ciphertext:`, `recovered:`, `same key new iv:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.