前言Introduction:隨機數是現代密碼學的基石。從 HTTPS 加密連線、密碼生成、數位簽章到區塊鏈,無處不依賴高品質的隨機數。但你知道嗎?並非所有「隨機數」都真正隨機,更不是所有隨機數都適合密碼學應用。本文將深入解析 PRNG(偽隨機)、TRNG(真隨機)、CSPRNG(密碼學安全隨機)的原理與差異,並透過真實攻擊案例,說明隨機數安全的重要性。: Random numbers are the cornerstone of modern cryptography. From HTTPS encrypted connections, password generation, digital signatures to blockchain, everything relies on high-quality random numbers. But did you know? Not all "random numbers" are truly random, and not all random numbers are suitable for cryptographic applications. This article will deeply analyze the principles and differences between PRNG (Pseudo-Random), TRNG (True Random), and CSPRNG (Cryptographically Secure Random), and explain the importance of random number security through real attack cases.
偽隨機數生成器 (PRNG) 原理圖,展示種子、算法和輸出序列的關係
一、隨機性的重要性:為什麼我們需要隨機數?1. The Importance of Randomness: Why Do We Need Random Numbers?
在資訊安全領域,In the field of information security, 不可預測性Unpredictability是最高原則。如果攻擊者能預測系統的行為,所有加密機制都形同虛設。隨機數扮演以下關鍵角色: is the highest principle. If attackers can predict system behavior, all encryption mechanisms become useless. Random numbers play the following key roles:
密鑰生成Key Generation:AES、RSA 等加密演算法的金鑰必須隨機產生,否則暴力破解時間大幅縮短: Keys for encryption algorithms like AES and RSA must be randomly generated, otherwise brute-force cracking time is greatly reduced
初始化向量(IV)Initialization Vector (IV):CBC、CTR 等加密模式需要隨機 IV,避免相同明文產生相同密文: Encryption modes like CBC and CTR require random IVs to prevent identical plaintexts from producing identical ciphertexts
Nonce(隨機數):防止重放攻擊(Replay Attack),確保每次請求唯一: Prevents replay attacks and ensures each request is unique
鹽值(Salt)Salt:密碼雜湊時加入隨機鹽,防止彩虹表攻擊: Adding random salt during password hashing prevents rainbow table attacks
會話令牌(Session Token)Session Token:網站登入後的身份憑證,必須不可預測: Identity credentials after website login, must be unpredictable
⚠️ 真實案例:Debian OpenSSL 弱隨機數漏洞(2008)Real Case: Debian OpenSSL Weak Random Number Vulnerability (2008)
2006-2008 年間,Debian Linux 的 OpenSSL 套件存在嚴重漏洞:隨機數生成器的Between 2006-2008, Debian Linux's OpenSSL package had a severe vulnerability: the random number generator's 熵源entropy source被意外移除,導致只能產生 32,767 種可能的金鑰(正常應有 2^128 種)。 was accidentally removed, resulting in only 32,767 possible keys (normally should be 2^128).
影響Impact:所有使用該版本 OpenSSL 生成的 SSH 金鑰、SSL 憑證、GPG 金鑰都可在數小時內暴力破解。全球數百萬伺服器受影響,需緊急更換所有金鑰。: All SSH keys, SSL certificates, and GPG keys generated with that version of OpenSSL could be brute-forced within hours. Millions of servers worldwide were affected and required emergency key replacement.
教訓Lesson:隨機數品質直接決定系統安全性,絕不能妥協。: Random number quality directly determines system security - never compromise on it.
真隨機數生成器 (TRNG) 工作原理圖,展示物理熵源和量子隨機性
二、PRNG(偽隨機數生成器):演算法的魔法2. PRNG (Pseudorandom Number Generator): The Magic of Algorithms
PRNG(Pseudorandom Number Generator,偽隨機數生成器)PRNG (Pseudorandom Number Generator)是透過 generates seemingly random sequences through 確定性演算法deterministic algorithms產生看似隨機的數列。給定相同的. Given the same 種子(Seed)seed,PRNG 會產生完全相同的輸出。, a PRNG will produce exactly the same output.
品質Quality:通過大多數隨機性測試: Passes most randomness tests
速度Speed:快: Fast
缺點Cons:: 不具密碼學安全性Not cryptographically secure,觀察 624 個連續輸出即可預測後續所有值, observing 624 consecutive outputs allows prediction of all subsequent values
2. PRNG 的致命弱點:可預測性2. The Fatal Weakness of PRNG: Predictability
所有 PRNG 的核心問題:The core problem with all PRNGs: 給定種子,輸出完全確定given a seed, the output is completely deterministic。如果攻擊者:. If an attacker:
知道演算法(通常是公開的)Knows the algorithm (usually public)
知道或猜測種子(如時間戳、process ID)Knows or guesses the seed (e.g., timestamp, process ID)
觀察到部分輸出Observes partial output
...就能預測所有未來輸出,破解加密系統。...they can predict all future outputs and break the encryption system.
⚠️ 真實案例:線上撲克網站隨機數漏洞(2013)Real Case: Online Poker Site Random Number Vulnerability (2013)
某線上撲克網站使用 Math.random()(基於時間戳的 LCG)產生洗牌順序。駭客透過:An online poker site used Math.random() (timestamp-based LCG) to generate shuffle sequences. Hackers exploited this by:
觀察多局遊戲的發牌順序Observing card dealing sequences across multiple games
推算伺服器時間戳(種子)Calculating the server timestamp (seed)
預測後續所有牌局Predicting all subsequent card games
結果Result:駭客贏得數百萬美元,網站倒閉。: Hackers won millions of dollars, and the site went bankrupt.
密碼學中隨機數的關鍵應用場景與安全最佳實踐,包含加密金鑰、初始向量、鹽值等用途
三、TRNG(真隨機數生成器):物理世界的混沌3. TRNG (True Random Number Generator): Chaos from the Physical World
TRNG(True Random Number Generator,真隨機數生成器)TRNG (True Random Number Generator)從 extracts randomness from 物理現象physical phenomena中提取隨機性,輸出完全不可預測。, producing completely unpredictable output.
1. TRNG 的熵源(Entropy Sources)1. Entropy Sources for TRNG
熵源Entropy Source
原理Principle
應用Application
放射性衰變Radioactive Decay
放射性同位素衰變的時間完全隨機(量子現象)Decay time of radioactive isotopes is completely random (quantum phenomenon)
HotBits 服務(使用銫-137)HotBits service (using Cesium-137)
電子熱噪音Thermal Electronic Noise
電阻中電子的隨機熱運動Random thermal motion of electrons in resistors
Intel RDRAND 指令Intel RDRAND instruction
大氣噪音Atmospheric Noise
雷電、無線電干擾產生的隨機訊號Random signals from lightning and radio interference
Random.org 服務Random.org service
鍵盤/滑鼠時序Keyboard/Mouse Timing
使用者操作的時間間隔(微秒級)Time intervals of user operations (microsecond level)
Linux /dev/random
硬碟 seek 時間HDD Seek Time
硬碟讀寫頭移動的微小時間差Tiny time differences in hard drive head movement
嵌入式系統Embedded systems
2. TRNG 的優缺點2. Pros and Cons of TRNG
✅ 優點Pros
完全不可預測Completely Unpredictable:即使知道所有歷史輸出,也無法預測下一個值: Even knowing all historical outputs, the next value cannot be predicted
無週期No Period:不會重複(在合理時間內): Will not repeat (within reasonable time)
最高安全性Highest Security:適用於最敏感的密碼學應用: Suitable for the most sensitive cryptographic applications
❌ 缺點Cons
速度慢Slow:需等待物理事件發生(如 /dev/random 可能阻塞): Must wait for physical events (e.g., /dev/random may block)
成本高High Cost:需特殊硬體(如輻射偵測器): Requires special hardware (e.g., radiation detectors)
可用性問題Availability Issues:熵源可能耗盡(如嵌入式設備無使用者輸入): Entropy sources may be exhausted (e.g., embedded devices without user input)
四、CSPRNG(密碼學安全隨機數):最佳平衡點4. CSPRNG (Cryptographically Secure Random): The Best Balance
CSPRNG(Cryptographically Secure Pseudorandom Number Generator)CSPRNG (Cryptographically Secure Pseudorandom Number Generator)是結合 PRNG 速度與 TRNG 安全性的方案: combines the speed of PRNG with the security of TRNG:
使用Use 密碼學演算法cryptographic algorithms(如 ChaCha20、AES-CTR)擴展種子 (e.g., ChaCha20, AES-CTR) to expand the seed
即使攻擊者知道部分輸出,也無法預測其他值Even if attackers know partial output, they cannot predict other values
1. CSPRNG 的核心要求1. Core Requirements of CSPRNG
向後安全性(Backtracking Resistance)Backtracking Resistance:即使當前狀態被洩露,過去的輸出仍無法推算: Even if current state is leaked, past outputs cannot be derived
向前安全性(Forward Security)Forward Security:過去的狀態被洩露,未來輸出仍不可預測(需定期重新播種): Past state leakage still cannot predict future outputs (requires periodic reseeding)
不可區分性Indistinguishability:輸出與真隨機數無法區分(通過所有統計測試): Output is indistinguishable from true random numbers (passes all statistical tests)
2. 常見 CSPRNG 實作2. Common CSPRNG Implementations
平台/語言Platform/Language
CSPRNG API
底層機制Underlying Mechanism
JavaScript (Browser)
crypto.getRandomValues()
作業系統 CSPRNG(/dev/urandom 或 CryptGenRandom)OS CSPRNG (/dev/urandom or CryptGenRandom)
Python
secrets模組module
/dev/urandom (Linux) 或or CryptGenRandom (Windows)
Java
SecureRandom
SHA1PRNG + /dev/urandom
Linux
/dev/urandom
ChaCha20 (Kernel 4.8+)
Windows
BCryptGenRandom
AES-CTR
五、隨機數品質測試:如何驗證隨機性?5. Random Number Quality Testing: How to Verify Randomness?
隨機數生成器的品質可透過The quality of random number generators can be verified through 統計測試套件statistical test suites驗證::
1. NIST SP 800-22 測試套件1. NIST SP 800-22 Test Suite
美國標準技術研究院(NIST)制定的 15 項統計測試:15 statistical tests defined by the National Institute of Standards and Technology (NIST):
頻率測試(Frequency Test)Frequency Test:0 和 1 的比例應接近 1:1: The ratio of 0s and 1s should be close to 1:1
區塊頻率測試Block Frequency Test:分段檢查 0/1 比例: Check 0/1 ratio in segments
遊程測試(Runs Test)Runs Test:連續相同值的長度分佈: Distribution of consecutive identical value lengths
二進位矩陣秩測試Binary Matrix Rank Test:檢查線性相關性: Check for linear dependencies
頻譜測試(FFT Test)Spectral Test (FFT):頻域分析,檢查週期性: Frequency domain analysis to check for periodicity
2. Diehard Tests2. Diehard Tests
經典隨機性測試套件(15 項測試),檢測:Classic randomness test suite (15 tests), detecting:
使用 CSPRNG 而非一般 PRNGUse CSPRNG instead of regular PRNG
定期重新播種(如每 10 分鐘從 /dev/urandom 注入新熵)Periodic reseeding (e.g., inject new entropy from /dev/urandom every 10 minutes)
限制單次輸出數量Limit single output quantity
3. 熵耗盡攻擊3. Entropy Exhaustion Attack
針對 Linux /dev/random(會阻塞直到有足夠熵)的 DoS 攻擊:DoS attack targeting Linux /dev/random (which blocks until sufficient entropy):
攻擊者大量請求隨機數,耗盡熵池Attackers request large amounts of random numbers, exhausting the entropy pool
合法服務因等待熵而停擺Legitimate services stall while waiting for entropy
防禦Defense:使用 /dev/urandom(不會阻塞,現代 Linux 已足夠安全)或硬體 RNG(Intel RDRAND)。: Use /dev/urandom (non-blocking, modern Linux is sufficiently secure) or hardware RNG (Intel RDRAND).
七、實作最佳實踐7. Implementation Best Practices
1. JavaScript/TypeScript
// ❌ 錯誤:絕不使用 Math.random() 做密碼學應用
const badToken = Math.random().toString(36).substring(2);
// ✅ 正確:使用 Web Crypto API
function generateSecureToken(length = 32) {
const array = new Uint8Array(length);
crypto.getRandomValues(array);
return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
}
const token = generateSecureToken(); // 64 位元組十六進位字串
console.log(token); // e.g., "a3f5c8d9e2b1..."
// 生成密碼學安全的隨機整數
function secureRandomInt(min, max) {
const range = max - min + 1;
const bytesNeeded = Math.ceil(Math.log2(range) / 8);
const maxValue = Math.pow(256, bytesNeeded);
const threshold = maxValue - (maxValue % range);
let randomValue;
do {
const randomBytes = new Uint8Array(bytesNeeded);
crypto.getRandomValues(randomBytes);
randomValue = randomBytes.reduce((acc, byte, i) => acc + byte * Math.pow(256, i), 0);
} while (randomValue >= threshold); // 避免模偏差
return min + (randomValue % range);
}
避免自行播種Avoid Manual Seeding:讓作業系統處理(現代 OS 的 CSPRNG 已自動從多個熵源收集): Let the OS handle it (modern OS CSPRNGs automatically collect from multiple entropy sources)
足夠的熵Sufficient Entropy:金鑰至少 128 位元(AES-128),256 位元更佳(AES-256): Keys should be at least 128 bits (AES-128), 256 bits is better (AES-256)
定期更新Regular Updates:長期運行的服務應定期重新初始化 CSPRNG: Long-running services should periodically reinitialize CSPRNG
避免模偏差Avoid Modulo Bias:生成範圍隨機數時,使用拒絕採樣(rejection sampling): When generating ranged random numbers, use rejection sampling
統計特性重於安全性Statistical properties matter more than security
結論:隨機數是安全的基石Conclusion: Random Numbers Are the Foundation of Security
隨機數看似簡單,實則是密碼學與資訊安全的基礎。本文的核心要點:Random numbers may seem simple, but they are the foundation of cryptography and information security. The core points of this article:
PRNG:快速但可預測,僅適合遊戲、模擬等非安全場景: Fast but predictable, only suitable for games, simulations, and other non-security scenarios
TRNG:完全隨機但速度慢,適合高安全需求(如 CA 根金鑰): Completely random but slow, suitable for high-security needs (e.g., CA root keys)
CSPRNG:平衡速度與安全,: Balances speed and security, 所有密碼學應用的標準選擇the standard choice for all cryptographic applications
測試隨機性Test Randomness:使用 NIST SP 800-22 或 TestU01 驗證自訂 RNG: Use NIST SP 800-22 or TestU01 to verify custom RNGs
警惕攻擊Beware of Attacks:種子預測、狀態洩露、熵耗盡都可能破壞安全: Seed prediction, state leakage, and entropy exhaustion can all compromise security
記住:Remember: 密碼學的安全性取決於最弱的一環Cryptographic security depends on the weakest link。即使使用 AES-256 這樣的強加密演算法,如果金鑰是用 Math.random() 生成的,整個系統形同裸奔。投資時間理解隨機數,是成為優秀資安工程師的必經之路。. Even with strong encryption algorithms like AES-256, if the key is generated with Math.random(), the entire system is exposed. Investing time to understand random numbers is essential to becoming an excellent security engineer.
🎲 試用我們的密碼學安全隨機數生成器Try Our Cryptographically Secure Random Number Generator
基於 Web Crypto API 的高品質隨機數生成器,適用於密碼生成、抽獎、密鑰生成等場景。100% 本地處理,保護您的隱私!A high-quality random number generator based on Web Crypto API, suitable for password generation, lotteries, key generation, and more. 100% local processing to protect your privacy!