开发者

Random Code Overkill?

开发者 https://www.devze.com 2023-04-06 18:53 出处:网络
I have some code I am using function genCode ($entropy=1) { $truCde = \"\"; $indx = 0; $leng = 30*$entropy;

I have some code I am using

function genCode ($entropy=1) {
    $truCde = "";
    $indx = 0;
    $leng = 30*$entropy;
    while ($indx < $leng) {
        $code = "";
        $length = 100*$entropy;
        $index = 0;
        while ($index < $length) {
            $code .= rand();
            $index++;
        }
        $index = 0;
        while ($index < $length) {
            $code = sha1($code);
            $index++;
        }
        $truCde .= $code;
        $indx++;
    }
    $finalCode = sha1(rand()) . hash("sha256",$truCde . md5($entropy*rand()));
    $finalCode .= sha1(md5(strlen($finalCode)*$entropy));
    return hash (
        "sha256",
        sha1($finalCode) . sha1(md5($final开发者_运维知识库Code)) . sha1(sha1($finalCode))
    );
}

to generate a random code for e-mail verification. Is there code that takes less time to generate random codes. It takes about 1-2 seconds to run this code, but I am looking to shave .7 seconds off this because the rest of the script will take longer.


That's massive overkill. Calling rand() repeatedly isn't going to make the code "more random", nor will using random combinations of SHA and MD5 hashes. None of that complexity improves the verification codes.

An improvement that would make a difference would be to use mt_rand() in preference to rand(). The Mersenne Twister pseudo RNG is much stronger than most default rand() implementations. The PHP documentation hints that rand() may max out at 215 meaning you can only generate 32,768 unique verification codes.

Other than that, a single hash call will do.

sha1(mt_rand())

(You don't even really need to call a hash function as the unpredictability of your codes will come from the random number generator, not the hash function. But hash functions have the nice side effect of creating long hex strings which "look" better.)


If you just want to generate random strings to test that someone has access to an email address, or something like that, I would throw out that code and use something a lot more straightforward. Something like the following would likely do.

function genCode () {
    $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
    $returnValue = '';
    for ($i = 0; $i < 20; $i++) {
        $returnValue .= $chars[mt_rand(0, 35)];
    }
    return $returnValue;
}

You can hash the return value if you want, but I don't know what the point would be other than to obfuscate the scheme used to come up with the random strings.

0

精彩评论

暂无评论...
验证码 换一张
取 消