openssl_random_pseudo_bytes

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

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

說明

openssl_random_pseudo_bytes(int $length, bool &$crypto_strong = ?): string

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

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

參數(shù)

length

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

crypto_strong

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

返回值

成功,返回生成的字節(jié)串 string , 或者在失敗時(shí)返回 false.

范例

示例 #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: 0
string(0) ""
NULL

Lengths: Bytes: 0 and Hex: 0
string(0) ""
NULL

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() - Generates cryptographically secure pseudo-random bytes
  • bin2hex() - 函數(shù)把包含數(shù)據(jù)的二進(jìn)制字符串轉(zhuǎn)換為十六進(jìn)制值
  • crypt() - 單向字符串散列
  • mt_rand() - 生成更好的隨機(jī)數(shù)
  • uniqid() - 生成一個(gè)唯一ID