Nathan Saper wrote:
> Here's one for you Perl gurus out there:
>
> In a Perl app I'm trying to write, I want to be able to create random
> hex integers $bits bits long, where $bits is a user-defined variable.
> The randomness of the numbers needs to be as good as possible, because
> it would be used in a crypto app.
>
> Any ideas?
Do it in C, and have the perl script take the output.. Perl isnt
really fast enough for this type of thing.
I have this sinking sensation, however, that your wanting to do this
for something that will be platform independant, and run on a
webserver... which makes the above impossible. Hmmm..
Anyways, heres a standalone application with a hard-coded number of
bits... it at least works well enough that you can call it from a bash
script to define a variable or some such..
The weird code at the front of the program (the xbits, or extra bits,
stuff) handles the event that the number of bits is NOT a multiple of
four.. in these cases, the digit first printed must be the one with
the limited range (0-7, 0-3, or 0-1) depending on the number of extra
bits.
--
#!/usr/bin/perl -w
#
# Random Hexadecimal Generator by Jason Kennerly
# Distrubute under the GPL - GNU General Public License
#
use strict;
$| = 1;
my( $base, $randigit, $count, $bits, $hexdigit, $xbits );
srand;
#
$bits = 16;
#
$count = int ( $bits / 4 );
$xbits = $bits - ( $count * 4);
if ($xbits > 0) {
$base = 2 ** $xbits;
$randigit = int( rand( $base) );
$hexdigit =
('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f')[$randigit];
print $hexdigit;
--$count;
}
#
$base = 16;
while ($count > 0){
$randigit = int( rand( $base) );
$hexdigit =
('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f')[$randigit];
print $hexdigit;
--$count;
}
#
exit( 0 );
--
jkenner @ mindspring . com__
I Support Linux: _> _ _ |_ _ _ _|
Working Together To <__(_||_)| )| `(_|(_)(_|
To Build A Better Future. | <s>