PHP8 openssl_random_pseudo_bytes

2024-03-13 11:24 更新

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_random_pseudo_bytes — 生成一個(gè)偽隨機(jī)字節(jié)串

說明

openssl_random_pseudo_bytes(int $length, bool &$strong_result = null): string

生成一個(gè)偽隨機(jī)字節(jié)串 string ,字節(jié)數(shù)由 length 參數(shù)指定。

通過 strong_result 參數(shù)可以表示在生成隨機(jī)字節(jié)的過程中是否使用了強(qiáng)加密算法。返回值為 false 的情況很少見,但已損壞或老化的有些系統(tǒng)上會出現(xiàn)。

參數(shù) 

length

所需字節(jié)串的長度,必須為正整數(shù)且小于等于 2147483647。PHP 會試著將該參數(shù)轉(zhuǎn)換為非空整數(shù)來使用它。

strong_result

如果傳遞到該函數(shù)中,將會保存為一個(gè) bool 值來表明是否使用了“強(qiáng)加密”,如果被用于GPG和密碼之類的將返回 true,否則返回 false

返回值 

返回生成的字節(jié) string。

錯(cuò)誤/異常 

openssl_random_pseudo_bytes() 失敗時(shí)拋出 Exception。

更新日志 

版本說明
8.0.0strong_result 現(xiàn)在可為 null。
7.4.0此函數(shù)失敗時(shí)不再返回 false,而是會拋出 Exception。

示例 

示例 #1 openssl_random_pseudo_bytes() 示例

<?php
for ($i = 1; $i <= 4; $i++) {
    $bytes = openssl_random_pseudo_bytes($i, $cstrong);
    $hex   = bin2hex($bytes);

    echo "Lengths: Bytes: $i and Hex: " . strlen($hex) . PHP_EOL;
    var_dump($hex);
    var_dump($cstrong);
    echo PHP_EOL;
}
?>

以上示例的輸出類似于:

Lengths: Bytes: 1 and Hex: 2
string(2) "42"
bool(true)

Lengths: Bytes: 2 and Hex: 4
string(4) "dc6e"
bool(true)

Lengths: Bytes: 3 and Hex: 6
string(6) "288591"
bool(true)

Lengths: Bytes: 4 and Hex: 8
string(8) "ab86d144"
bool(true)

參見 

  • random_bytes() - Get cryptographically secure random bytes
  • bin2hex() - 將二進(jìn)制數(shù)據(jù)轉(zhuǎn)換為十六進(jìn)制表示
  • crypt() - 單向字符串散列
  • random_int() - 獲取生成加密安全、均勻分布的整數(shù)


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號