lundi 22 décembre 2014

PHP - How to create a secure 10 digits key

Well, i need a way to create a random unique key of 10 digits that matchs to the follow pattern:


LLNNNLLNNN


where L is a letter and N is a number.


I have found a solution but i'm looking for some smart opinion. My solution was (php):



$alhpabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','W','Y','Z']; //26 letras
$transaction_id = ''; //string

//Two first letters
$transaction_id .= $alhpabet[secure_random_number(0,25)];
$transaction_id .= $alhpabet[secure_random_number(0, 26)];
//3 first numbers (3 digits)
$transaction_id .= str_pad(secure_random_number(0, 999),3,'0',STR_PAD_LEFT);
//last letters
$transaction_id .= $alhpabet[secure_random_number(0,25)];
$transaction_id .= $alhpabet[secure_random_number(0, 26)];
//last numbers
$transaction_id .= str_pad(secure_random_number(0, 999),3,'0',STR_PAD_LEFT);


My function to generate secure_random_number is:



function secure_random_number($min, $max){
$range = $max - $min;
if($range == 0)
return $min; // not so random...
$log = log($range, 2);
$bytes = (int) ($log / 8) + 1; // length in bytes
$bits = (int) $log + 1; // length in bits
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1
do{
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes, $s)));
$rnd = $rnd & $filter; // discard irrelevant bits
}while($rnd >= $range);
return $min + $rnd;
}


ps: i get this somewhere in here, but forget to note the credits...


NOTE: I'm not worried about performance.





Aucun commentaire:

Enregistrer un commentaire