PHP CSPRNG登入

PHP CSPRNG

CSPRNG(Cryptographically Secure Pseudo-Random Number Generator,偽隨機數產生器)。

PHP 7 透過引入幾個 CSPRNG 函數提供一個簡單的機制來產生密碼學上強壯的隨機數。

  • random_bytes() - 加密生存被保護的偽隨機字串。

  • random_int() - 加密生存被保護的偽隨機整數。


random_bytes()

語法格式

string random_bytes ( int $length )

參數

  • length - 隨機字串傳回的位元組數。

傳回值

  • 傳回字串,接受一個int型入參代表傳回結果的位元組數。

實例

<?php
$bytes = random_bytes(5);
print(bin2hex($bytes));
?>

以上程式執行輸出結果為:

6f36d48a29

random_int()

#語法格式

int random_int ( int $min , int $max )

參數

  • min - 傳回的最小值,必須是大於或等於PHP_INT_MIN 。

  • max - 傳回的最大值,必須是小於或等於 PHP_INT_MAX 。

傳回值

  • 傳回指定範圍內的int型數字。

實例

<?php
print(random_int(100, 999));
print(PHP_EOL);
print(random_int(-1000, 0));
?>

以上程式執行輸出結果為:

723
-64
下一節
<?php $bytes = random_bytes(5); print(bin2hex($bytes)); ?>
章節課件