Skip to content

Commit

Permalink
Use urandom for random_string
Browse files Browse the repository at this point in the history
It should improve randomness
  • Loading branch information
andrii-suse committed Nov 28, 2024
1 parent 880c37c commit 46ace3a
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion lib/MirrorCache/Utils.pm
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,20 @@ sub random_string {
my ($length, $chars) = @_;
$length //= 16;
$chars //= ['a' .. 'z', 'A' .. 'Z', '0' .. '9', '_'];
return join('', map { $chars->[rand @$chars] } 1 .. $length);
my $upper = @$chars;
return join('', map { $chars->[_random_int_safe($upper)] } 1 .. $length);
}

# this will reliably work only for $upper < 1000000000
sub _random_int_safe {
my ($upper) = @_;
my $length = 4;
open(my $fd, '<:raw:bytes', '/dev/urandom') || die "can't open /dev/urandom: $!";
read($fd, my $bytes, $length) || die "can't read random byte: $!";
close $fd;

my $res = unpack("N", $bytes);
return int($res) % $upper;
}

sub datetime_now() {
Expand Down

0 comments on commit 46ace3a

Please sign in to comment.