Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I want to use this function to store 1024 bit keys in my Mysql database. If you call generateKey(128), you'll get a 128 byte string, same as 1024 bit string. I want to know if there is something wrong with this code or if I should be worried about inter-operability issues with MySQL, Java, Android, File Read/Write, etc.

    public function generateKey($size){

    $randomString = "";
    $charUniverse = "";
    for($i=0;$i<256;$i++){
        $charUniverse .= chr($i);
    }
    for($i=0;$i<$size;$i++){
        $randInt=mt_rand(0, strlen($charUniverse)-1);
        $randChar=$charUniverse[$randInt];
        $randomString=$randomString.$randChar;
    }
    return $randomString;     
}
share|improve this question

1 Answer 1

up vote 3 down vote accepted
  • Use chr($randInt) instead of $charUniverse[$randInt], and abandon the $charUniverse variable altogether.
  • Use the $str .= "str" dot-equals operator in PHP to append to your final string.

Thus your code becomes:

public function generateKey($size){

   $randomString = "";
   $charDomainSize = 256;
   for($i=0;$i<$size;$i++){
     $randInt=mt_rand(0, $charDomainSize-1);
     $randChar=chr($randInt);
     $randomString .= $randChar;
   }
   return $randomString; 

}

If we compress your code further, it becomes:

public function generateKey($size){
   $randomString = "";
   for($i=0;$i<$size;$i++){
      $randomString .= chr(mt_rand(0, 255));
   }
   return $randomString;
}

I conducted a speed test, as well. The new code is faster (1000 runs, varied sizes between 1128 and 1148). The units are seconds.

  • Function 1 Average: 0.024438648223877
  • Function 2 Average: 0.015253195762634

Only using 256 as a size, 1000 runs:

  • Function 1 Average: 0.00031177306175232
  • Function 2 Average: 0.00017282342910767

This is a little overkill, but I was bored.

It should be very easy to port your random string generator to other platforms, although it may develop more or less dependable randomness based on the underlying generators. E.g. don't use Java's java.util.Random for security or scientific purposes (see Difference between java.util.Random and java.security.SecureRandom).

You might also want to consider PHP's openssl_random_pseudo_bytes, depending on your intent. That may not be as easily ported, though, as your current code.

share|improve this answer
    
brilliant coding, thank you for your time –  cristi _b Dec 10 '12 at 19:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.