>本文研究了在密碼學中使用隨機數生成的挑戰,強調了PHP 5和PHP 7之間的差異。 PHP5缺少可用的機制來生成密碼固定的隨機數,而PHP 7則引入random_bytes
和random_int
了解csprngs
>密碼固定的偽數字生成器(CSPRNG)是專為加密應用設計的PRNG。 它的關鍵特徵是高質量的隨機性,至關重要:>
random_bytes
php 7提供random_int
(返回指定字節長度的字符串)和
random_bytes
示例:
$bytes = random_bytes(10); var_dump(bin2hex($bytes)); // Possible output: string(20) "7dfab0af960d359388e6"
random_int
示例:
var_dump(random_int(1, 100)); // Possible output: 27
這些功能根據操作系統使用各種隨機性來源,優先考慮安全選項,例如CryptGenRandom
(Windows),arc4random_buf
(bsd),getrandom(2)
>(linux),最後/dev/urandom
作為後備。 如果找不到合適的來源,就會丟棄錯誤。
測試隨機性
評估隨機數發生器的質量涉及統計測試。一個簡單的例子是模擬骰子卷。 可以將滾動三分骰子1,000,000次滾動結果的預期分佈與random_int
>和標準rand
函數產生的實際結果進行比較。
一個代碼示例(簡化為簡潔)和比較圖(如下所示)表明,random_int
>表現出更接近預期值的分佈,表明與rand
>
> php 5替代
<🎜php5 php 5缺少內置的csprngs。 解決方法包括,openssl_random_pseudo_bytes()
,或直接訪問mcrypt_create_iv()
>或/dev/random
>。 諸如Randomlib或libsodium之類的圖書館提供其他解決方案。 /dev/urandom
庫random_compat
>
庫提供了 一個簡單的密碼生成示例,使用
使用CSPRNG對於安全應用程序至關重要。 庫為PHP 5提供了向後兼容的解決方案,而PHP 7的開發人員應直接利用 。 優先考慮可靠的隨機數會顯著增強應用程序安全性。 以上是PHP中的隨機性 - 您感到幸運嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!random_compat
>和random_bytes
功能。 它可以通過作曲家(random_int
)安裝,並以下內容使用:$bytes = random_bytes(10);
var_dump(bin2hex($bytes));
// Possible output: string(20) "7dfab0af960d359388e6"
/dev/urandom
:random_compat
var_dump(random_int(1, 100));
// Possible output: 27
random_compat
random_bytes
進一步閱讀random_int
確認
感謝Scott Arciszewski的同行評審協助。
Description
Link
Die Hard Test
https://www.php.cn/link/1852a2083dbe1c2ec33ab9366feb2862
Chi-square test with dice example
https://www.php.cn/link/fb6a253729096c1e92e43c26a6fdadc3
Kolmogorov-Smirnov Test
https://www.php.cn/link/030d13e49bb7d1add5ac5ea2e4a43231
Spectral Test
https://www.php.cn/link/6bbd80b04535d39be5e02dbfd8730469
RaBiGeTe test suite
https://www.php.cn/link/e626afbcdb83368b3491c0c473da19f1
Random Number Generation In PHP (2011)
https://www.php.cn/link/f7ff233e4ed3e6b13c5d5c7a9201e4ec
Testing RNG part 1 and 2
https://www.php.cn/link/a1c71b134d46d7f7ff00f488874a8d43, https://www.php.cn/link/2e3517ba49c2a7c999b9c8381185ae4e