random_bytes
(PHP 7)
random_bytes — Generates cryptographically secure pseudo-random bytes
説明
random_bytes
( int
$length
) : stringGenerates an arbitrary length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors.
この関数が使う不規則性のソースはつぎのとおりです。
- Windows では、常に » CryptGenRandom() を使います。PHP 7.2.0 以降は、常に » CNG-API を使うようになりました。
- Linux では、システムコール » getrandom(2) があればそれを使います。
- その他のプラットフォームでは、 /dev/urandom を使います。
- これらがいずれも使えない場合は、 Exception をスローします。
注意: この関数は PHP 7.0 で追加されたものですが、PHP 5.2 から 5.6 までのバージョンで使える » ユーザーランドの実装 も公開されています。
パラメータ
-
length -
The length of the random string that should be returned in bytes.
返り値
Returns a string containing the requested number of cryptographically secure random bytes.
エラー / 例外
例
例1 random_bytes() example
<?php
$bytes = random_bytes(5);
var_dump(bin2hex($bytes));
?>
上の例の出力は、 たとえば以下のようになります。
string(10) "385e33f741"
参考
- random_int() - Generates cryptographically secure pseudo-random integers
- openssl_random_pseudo_bytes() - 疑似乱数のバイト文字列を生成する
- bin2hex() - バイナリのデータを16進表現に変換する