生成 cryptographic nonces correctly
nonce (数字 used 一次) 必须是 唯一 per 加密在 相同键. Learn 当到 use random vs counter nonces 和 consequences 的 reuse.
- 1
nonce 必须从不 repeat 在相同键. Two approaches: (1) random nonce — 生成 96 bits 从 CSPRNG, collision 概率是 negligible 具有 96-位 space; (2) counter nonce — maintain monotonic counter, guaranteed 唯一但 requires persistent 声明. Random 是 simpler; counter 是 deterministic.
- 2 随机字节生成器 →
生成 a 96-bit (12-byte) random nonce. This is the standard size for AES-GCM. With 96 bits, the probability of collision after 2^32 encryptions is less than 2^-32 (birthday bound) — safe for most applications.
- 3 哈希计算器 →
如果你 need deterministic nonce 从消息 identifier, use hash: nonce = H(message_id). 此是 useful 当相同消息必须生成相同 ciphertext (deterministic 加密), 但是 careful — 它 reveals 如果 two messages 是 identical.
- 4
从不 use: timestamps (能够 repeat 开快 machines), Math.random() (不 cryptographic), hardcoded 常量, 或 counter 该 wraps around. 为 AES-GCM 具体而言, 96-位 nonces 是 optimal — 其他 sizes require additional 过程和 可以 weaken 安全.
常见问题
- Random 或 counter nonce?
- Random 是 simpler 和 stateless — use 它为 最多 applications. Counter 是 deterministic 和 avoids birthday-bound concerns, 但 requires persistent 声明和 fails 如果 counter resets (e.g., 服务器 restart). 为 AES-GCM, NIST recommends 96-位 random nonces.
- 什么如果 I accidentally reuse nonce?
- 为 GCM, nonce reuse 是 catastrophic — 它 leaks 认证键 和 allows forgery. 为 CTR, 它 leaks XOR 的 two plaintexts. 如果你 suspect reuse, immediately rotate 加密键 和 re-加密所有数据具有新 nonces.