<?php
class TokenGenerator
{
const ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
public function generateToken($length = 16)
{
$alphabetSize = strlen(self::ALPHABET);
$token = '';
while (strlen($token) < $length) {
$randomBytes = $this->generateRandomBytes(32);
$offset = abs(hexdec(bin2hex(substr($randomBytes, 0, 4)))) % $alphabetSize;
$token .= substr(self::ALPHABET, $offset, 1);
}
return $token;
}
private function generateRandomBytes($length)
{
$bytes = '';
// pre-fill with weak bytes
while (strlen($bytes) < $length) {
$bytes .= chr(mt_rand(0, 255));
}
// merge with mcrypt iv
if (function_exists('mcrypt_create_iv')) {
$bytes = hash_hmac('sha256', $bytes, mcrypt_create_iv($length, MCRYPT_DEV_URANDOM), true);
}
// merge with openssl bytes
if (function_exists('openssl_random_pseudo_bytes')) {
$bytes = hash_hmac('sha256', $bytes, openssl_random_pseudo_bytes($length), true);
}
// merge with urandom
if (file_exists('/dev/urandom') && is_readable('/dev/urandom')) {
$bytes = hash_hmac('sha256', $bytes, file_get_contents('/dev/urandom', null, null, null, $length), true);
}
return substr($bytes, 0, $length);
}
}
$gen = new TokenGenerator();
var_dump($gen->generateToken(10));
var_dump($gen->generateToken(10));
var_dump($gen->generateToken(10));
var_dump($gen->generateToken(20));
var_dump($gen->generateToken(20));
var_dump($gen->generateToken(20));
Abusive script
This script was stopped while abusing our resources
preferences:
32.51 ms | 402 KiB | 5 Q