PHP最快的方法生成随机数和散列em?

时间:2014-05-16 17:44:31

标签: php string hash sha256

我制作了一个脚本,可以生成随机64个长度的字符串,散列并将这些字符串存储在.txt文件中!

<?php
/**
 * Created by PhpStorm.
 * User: Ali
 * Date: 5/16/14
 * Time: 3:13 PM
 */
set_time_limit('60');
ini_set('max_execution_time', 60);
include("timer.php");
$timer = new timer();
$timer->start();
function random_text( $type = 'alnum', $length = 64 )
{
    switch ( $type ) {
        case 'alnum':
            $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._';
            break;
        case 'alpha':
            $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            break;
        case 'hexdec':
            $pool = '0123456789abcdef';
            break;
        case 'numeric':
            $pool = '0123456789';
            break;
        case 'nozero':
            $pool = '123456789';
            break;
        case 'distinct':
            $pool = '2345679ACDEFHJKLMNPRSTUVWXYZ';
            break;
        default:
            $pool = (string) $type;
            break;
    }


    $crypto_rand_secure = function ( $min, $max ) {
        $range = $max - $min;
        if ( $range < 0 ) return $min; // not so random...
        $log = log( $range, 2 );
        $bytes = (int) ( $log / 8 ) + 1; // length in bytes
        $bits = (int) $log + 1; // length in bits
        $filter = (int) ( 1 << $bits ) - 1; // set all lower bits to 1
        do {
            $rnd = hexdec( bin2hex( openssl_random_pseudo_bytes( $bytes ) ) );
            $rnd = $rnd & $filter; // discard irrelevant bits
        } while ( $rnd >= $range );
        return $min + $rnd;
    };

    $token = "";
    $max = strlen( $pool );
    for ( $i = 0; $i < $length; $i++ ) {
        $token .= $pool[$crypto_rand_secure( 0, $max )];
    }
    return $token;
}
ob_start();
$i = 0;
$times_to_run = 80000;
$array = array();
while ($i++ < $times_to_run)
{
   $string = random_text();
   $hash = hash('sha256', $string);
   $print = $string . ':'.$hash.' ';
   echo $print;
}
$result = ob_get_contents();
ob_end_clean();
echo $file_name;
$exploded = explode(" ", $result);
$date = date("Y-m-d-h-i-s");
$file_name = $date . '.txt';
$handle = fopen($file_name, "w") or die("Cannot Create File! (".$file_name.")");
foreach($exploded as $str)
{
    fwrite($handle, $str);
    fwrite($handle, "\r\n");
}
$timer->stop();
echo $timer->result();

当运行这个脚本(当前80k字符串)时,一旦我达到60秒的执行时间,我得到一个超时消息(tcp)...我看到我有两个txt文件,每个文件有80002个字符串,我想知道为什么双文本文件而不是一个? 另一个问题,我怎样才能加快php脚本的速度?可能会得到一个更高级的主机? 我需要在短时间内产生10 ^ 12个哈希值,在2分钟内产生160k哈希值将花费大量时间来完成... 谢谢开发人员!

1 个答案:

答案 0 :(得分:0)

为什么要使用OpenSSL随机方法?您可以使用mt_randarray_rand

$chars = str_split($pool);
$str = ''; 
for ($i=0; $i<64; $i++) {
    // Either:
    $str .= $chars[mt_rand(0, count($chars)-1)];
    // Or:
    // $str .= $chars[array_rand($chars)];
}

return $str;