openssl_random_pseudo_bytes

(PHP 5 >= 5.3.0, PHP 7)

openssl_random_pseudo_bytes疑似乱数のバイト文字列を生成する

説明

openssl_random_pseudo_bytes ( int $length [, bool &$crypto_strong ] ) : string

疑似乱数のバイト文字列を生成します。長さは length パラメータで指定します。

暗号学的に強いアルゴリズムを使って疑似乱数を生成したかどうかを知ることもできます。 オプションのパラメータ crypto_strong を使います。 これが FALSE になることはまずないでしょうが、 古いシステムなどではそうなることもあります。

パラメータ

length

希望するバイト長。正の整数でなければなりません。PHP は、 このパラメータを非 null の整数値にキャストして利用します。

crypto_strong

これを渡しておくと、使ったアルゴリズムが暗号学的に強いものであるかどうかを表す boolean 値が格納されます。「強い」とは、 GPG やパスワードなどに使っても安全であるという意味です。強い場合は TRUE、そうでない場合は FALSE となります。

返り値

成功した場合は指定したバイト長の string を返します。失敗した場合に 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() - バイナリのデータを16進表現に変換する
  • crypt() - 文字列の一方向のハッシュ化を行う
  • mt_rand() - メルセンヌ・ツイスター乱数生成器を介して乱数値を生成する
  • uniqid() - 一意な ID を生成する