PHP 中的隨機數——你以爲可靠麼?

本文主要分析以加密爲目的的隨機數生成問題。PHP 5 並未提供生成強加密隨機數的簡便機制,可是,PHP 7 引入了兩個 CSPRNG 函數以解決該問題。系 OneAPM 工程師編譯整理。php

PHP 中的隨機數——你以爲可靠麼?

什麼是 CSPRNG?

引用維基百科的定義,密碼安全的虛擬隨機數生成器(Cryptographically Secure Pseudorandom Number Generator,CSPRNG)是帶有特定屬性使之在密碼學中適用的虛擬隨機數生成器(pseudo-random number generator,PRNG)。html

CSPRNG 主要用於:linux

  • 生成鍵(好比:生成複雜的鍵)
  • 爲新的用戶帳號生成隨機密碼
  • 加密系統

保證高安全水準的一個重要因素即是高質量的隨機數。git

PHP 7 中的 CSPRNG

PHP 7 爲 CSPRNG 引入了兩種新函數:random_bytesrandom_intgithub

random_bytes 函數返回 string 類型,並接受一個 int 類型爲參數,該參數規定了所返回字符串的字節長度。安全

例如:服務器

$bytes = random_bytes('10');
var_dump(bin2hex($bytes));
//possible ouput: string(20) "7dfab0af960d359388e6"

random_int 函數返回給定範圍內的整型數字。composer

舉例:dom

var_dump(random_int(1, 100));
//possible output: 27

幕後解密

以上函數的隨機數來源因環境不一樣而有所差別:函數

  • 在 Windows 系統,會使用 CryptGenRandom() 函數。
  • 在其餘平臺,會優先使用 arc4random_buf() 函數(限 BSD 衍生系統或帶 libbsd 的系統)。
  • 若以上兩點均不符合,會使用 Linux [getrandom(2)](http://man7.org/linux/man-pages/man2/ getrandom.2.html) 系統調用。
  • 若以上來源均不符合,會拋出 Error

一個簡例

一個好的隨機數生成系統能確保生成質量適合的隨機數。爲了檢驗質量,須要運行一系列的統計試驗。此處,暫不深刻討論複雜的統計話題,將已知的行爲與隨機數生成器的結果進行比較,有助於質量評估。

一個簡單的測試方法是擲骰遊戲。假設投擲一次,投出6的機率是1/6。若是同時投擲三個骰子,投100次,投得零次、一次、兩次及三次6的次數大概是:

  • 0 次6 = 57.9 次
  • 1 次6 = 34.7 次
  • 2 次6 = 6.9 次
  • 3 次6 = 0.5 次

如下是骰子投擲100萬次的代碼:

$times = 1000000;
$result = [];
for ($i=0; $i<$times; $i++){
    $dieRoll = array(6 => 0); //initializes just the six counting to zero
    $dieRoll[roll()] += 1; //first die
    $dieRoll[roll()] += 1; //second die
    $dieRoll[roll()] += 1; //third die
    $result[$dieRoll[6]] += 1; //counts the sixes
}
function roll(){
    return random_int(1,6);
}
var_dump($result);

用 PHP 7 的 random_int 與簡單的 rand 函數測試上面的代碼,可能會獲得:

<table> <thead> <tr> <th>Sixes</th> <th>expected</th> <th>random_int</th> <th>rand</th> </tr> </thead> <tbody><tr> <td>0</td> <td>579000</td> <td>579430</td> <td>578179</td> </tr> <tr> <td>1</td> <td>347000</td> <td>346927</td> <td>347620</td> </tr> <tr> <td>2</td> <td>69000</td> <td>68985</td> <td>69586</td> </tr> <tr> <td>3</td> <td>5000</td> <td>4658</td> <td>4615</td> </tr> </tbody></table>

更直觀地查看 randrandom_int 的差異,能夠運用方程式放大兩組結果的差別,並繪製成圖表:

php result - expected result / sqrt(expected)

獲得的結果以下:

PHP 中的隨機數——你以爲可靠麼? (結果越接近零越好)

即使三個6的組合表現通常,且該測試與真實應用相比太過簡單,咱們也能清楚地看到 random_int 的表現優於 rand。何況,隨機數生成器的可預見行爲、重複行爲越少,應用的安全程度就更高。

PHP 5 又如何呢?

默認狀況下,PHP 5 並未提供任何強虛擬隨機數生成器。而實際使用中,能夠使用 openssl_random_pseudo_bytes()mcrypt_create_iv() 方法,或直接結合使用 /dev/random/dev/urandomfread() 方法。此外,還有包 RandomLiblibsodium

若是你想用一個比較好的隨機數生成器,同時能與 PHP 7 兼容,你能夠使用 Paragon Initiative 公司的 random_compat 庫。該庫容許在 PHP 5.x 項目中使用 random_bytes()random_int() 方法。

該庫能夠使用 Composer 進行安裝:

composer require paragonie/random_compat
require 'vendor/autoload.php';
$string = random_bytes(32);
var_dump(bin2hex($string));
// string(64) "8757a27ce421b3b9363b7825104f8bc8cf27c4c3036573e5f0d4a91ad2aaec6f"
$int = random_int(0,255);
var_dump($int);
// int(81)

random_compat 庫使用了與 PHP 7 中不一樣的優先序列:

  1. 若是可用,先使用 fread() /dev/urandom
  2. mcrypt_create_iv($bytes, MCRYPT_CREATE_IV)
  3. COM('CAPICOM.Utilities.1')->GetRandom()
  4. openssl_random_pseudo_bytes()

想了解爲什麼採用這一優先序列,能夠閱讀本文檔

使用該庫生成密碼的簡單案例以下:

$passwordChar = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$passwordLength = 8;
$max = strlen($passwordChar) - 1;
$password = '';
for ($i = 0; $i < $passwordLength; ++$i) {
    $password .= $passwordChar[random_int(0, $max)];
}
echo $password;
//possible output: 7rgG8GHu

總結

你應該儘可能使用在密碼學上安全的虛擬隨機數生成器。random_compat 庫爲此提供了很好的實現方法。

若是你想使用可靠的隨機數來源,正如前文所述,儘快開始使用 random_intrandom_bytes 吧!

原文地址:http://www.sitepoint.com/randomness-php-feel-lucky/

OneAPM for PHP 可以深刻到全部 PHP 應用內部完成應用性能管理 可以深刻到全部 PHP 應用內部完成應用性能管理和監控,包括代碼級別性能問題的可見性、性能瓶頸的快速識別與追溯、真實用戶體驗監控、服務器監控和端到端的應用性能管理。想閱讀更多技術文章,請訪問 OneAPM 官方技術博客

相關文章
相關標籤/搜索