Reputation: 4199
I need to select random characters from a set of characters say 0..9,a-z,A-z etc. For this I need to generate random integer number between 0-n ( n is the number of different characters) using Perl script. But Perl rand function is not cryptographically-secure. What is the best way to generate random number.
Right now I am using my own algorithm where I have chosen the character string randomly. Then I am generating a random number using rand. Using which I am selecting a decimal number among the random set of numbers.Then multiplying it with the random number. Whatever i am getting is the index of the characters chosen.
my @chars = ('a'..'d','#','N'..'Z','$','e'..'f','0'..'9');
my @random_numbers_list = ('1.0145','1.3464','1.8453','1.5145','1.9994');
my $random_string;
my $random_number;
my $chars_length = scalar @chars;
foreach (1 .. $length) {
$random_number = (rand $chars_length)*$random_numbers_list[rand(5)];
$random_number = ($random_number>$chars_length)?$random_number-$chars_length:$random_number;
$random_string .= $chars[$random_number];
}
print $random_string;
I know i keep on increase the random_numbers_list size, it will be more and more secure. But still i am not sure that it is the best way to achieve this.
Please let me know the best approach to generate a cryptographically-secure random string/number.
Thanks
Upvotes: 2
Views: 3007
Reputation: 137398
Math::Random::Secure
is one solution (utilizes /dev/urandom
on Linux).
Crypt::Random
is probably a better solution (utilizes /dev/random
, and as such, may block).
Upvotes: 6
Reputation: 13792
On the other hand, you have Perl modules at CPAN that gives you that funcionallity, like String::Random
Upvotes: -5