暗号学的にも強いランダムな文字列を作る方法。
他にもいろいろ方法があるけどひとまず openssl_random_pseudo_bytes()
を使ってみた。
random.php
/**
* 指定された桁数のランダム文字列を生成する
* (古い環境では暗号学的な強さにならない場合もあるが、ほとんどの環境は問題ない)
*
* @param int $length 求める文字列の長さ(桁数)
* @param string $chars ランダム文字列に使用したい文字一覧
*/
function randomstr($length, $chars)
{
$retstr = '';
$data = openssl_random_pseudo_bytes($length);
$num_chars = strlen($chars);
for ($i = 0; $i < $length; $i++)
{
$retstr .= substr($chars, ord(substr($data, $i, 1)) % $num_chars, 1);
}
return $retstr;
}
// 16進数の範囲で16桁の文字列を生成する場合
$rand1 = randomstr(16, '0123456789ABCDEF');
// 32進数(Base32)の範囲で16桁の文字列を生成する場合
$rand2 = randomstr(16, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567');
// 英数大小文字の範囲で16桁の文字列を生成する場合
$rand3 = randomstr(16, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');