Christopher Rioja
Christopher Rioja

Reputation: 149

About Generating Random Unique and Secure PHP Strings

Hi guys I have a code to generate random unique strings, 12 charactes long.

$random_string = sha1(uniqid(rand(10, 1000), true));
$random_string  = substr($random_string  , rand(0, strlen($random_string  ) - 12), 12);

Is my code above safe for collision? Any suggestions or modification to my above code?

Thanks guys!

Upvotes: 0

Views: 145

Answers (1)

OneOfOne
OneOfOne

Reputation: 99431

Maybe you should look into openssl_random_pseudo_bytes :

//returns 6 random bytes and in turn, bin2hex will make it a 12 characters string.
$rand = bin2hex(openssl_random_pseudo_bytes(6)); 

//edit workaround :

<?php
if(!function_exists('openssl_random_pseudo_bytes')) {
    // doesn't use open ssl but you get the idea.
    function openssl_random_pseudo_bytes($len) {
        return file_get_contents('/dev/urandom', false, NULL, -1, $len); 
    }
}
$rand = bin2hex(openssl_random_pseudo_bytes(6));

Upvotes: 2

Related Questions