0

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!

4
  • 1
    Adding more calls to randomisation and hashing won't make your string "more random" or "more secure". What makes you think uniqid won't be enough? Commented Oct 15, 2013 at 13:34
  • You cut part of sha1 hash, this most likely increase chance of collisions Commented Oct 15, 2013 at 13:41
  • When I remove the hashing(sha1), I get a string with "." which I dont want to happen. :( Commented Oct 15, 2013 at 13:45
  • 1
    What are these random strings going to be used for? Chances are there's a standard best-practice way of doing whatever it is you want to do. If you tell us what you'er actually trying to achieve, we might be able to give you better advice about how to do it. Commented Oct 15, 2013 at 14:02

1 Answer 1

2

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));
Sign up to request clarification or add additional context in comments.

4 Comments

random pseudo-bytes, or pseudo-random bytes ? Gotta love those function names.
PHP function names in general are completely random and meaningless, annoying as hell in times.
@OneofOne I test you code, and it giving me an error "Call to undefined function openssl_random_pseudo_bytes()"
I just want a random and unique alphanumeric with 12 characters long that I can store into my database. Please help? :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.