#!/usr/bin/perl
use strict;
use warnings;

# randBytes
# This script takes one command-line parameter specifying the number of bytes
# desired in the output.
# The script outputs (to STDOUT) the specified number of random bytes.
# The random numbers come from /dev/random
# Cameron Hayne (macdev@hayne.net), August 2006

die "usage: randBytes desiredNumBytes\n" if $#ARGV < 0;
my $desiredNumBytes = $ARGV[0];

my $buffsize = 64 * 1024; # experiment with different buffer sizes
if ($desiredNumBytes < $buffsize)
{
    $buffsize = $desiredNumBytes;
}
my $buffer;
my $numLeft = $desiredNumBytes;
open(RAND, "/dev/random") or die "Can't open /dev/random: $!\n";
while ($numLeft > 0)
{
    my $nread = read(RAND, $buffer, $buffsize);
    if ($nread <= $numLeft)
    {
        print $buffer;
        $numLeft -= $nread;
    }
    else
    {
        print substr($buffer, 0, $numLeft);
        $numLeft = 0;
    }
}
close(RAND);

