Run
Run

Reputation: 57176

openssl random pseudo bytes - repeatable?

I found this openssl_random_pseudo_bytes functions from php.net.

function generate_password($length = 24) {

    if(function_exists('openssl_random_pseudo_bytes')) {
        $password = base64_encode(openssl_random_pseudo_bytes($length, $strong));
        if($strong == TRUE)
            return substr($password, 0, $length); //base64 is about 33% longer, so we need to truncate the result
    }

    # fallback to mt_rand if php < 5.3 or no openssl available
    $characters = '0123456789';
    $characters .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+'; 
    $charactersLength = strlen($characters)-1;
    $password = '';

    # select some random characters
    for ($i = 0; $i < $length; $i++) {
        $password .= $characters[mt_rand(0, $charactersLength)];
    }        

    return $password;
}

But I want to be sure that whether the value it generates is repeatable or not? I am looking for a result which is not repeatable.

I have been told that the value from mt_rand() is not repeatable? but a random number should be repeatable as it self-explained already - mt_rand, doesn't it?

EDIT:

for instance, I just tested it and it has generated W8hhkS+ngIl7DxxFDxEx6gSn. but if will generate the same value again in the future - then it is repeatable.

Upvotes: 0

Views: 3671

Answers (2)

Agrajag
Agrajag

Reputation: 1034

random_pseudo_bytes is not repeatable. It is true that any output of finite length must eventually repeat, for example if you specify a length of 1 byte, then there is only 256 possible strings, so you must get the same string you had before no later than after 256 attempts (and likely quite a bit sooner).

But you're talking practically and not mathemathically, and have a default length of 24.

Yes, picking random 24-byte strings will eventually give you a string that you had before, but that's only true in the mathemathical universe. In the real physical universe, there's 6277101735386680763835789423207666416102355444464034512896 possible such strings, which means that even if you generated billions of passwords this way every second, you'd still not be likely to get the same string twice in a million years.

Upvotes: 6

Roman
Roman

Reputation: 523

Any random function, including the one above, is repeatable.
Perhaps you're looking for the PHP function uniqid?

Upvotes: 0

Related Questions