Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

A better rand() for Win32

by bitshiftleft (Sexton)
on Jul 30, 2007 at 18:08 UTC ( [id://629622]=sourcecode: print w/replies, xml ) Need Help??
Category: cryptography
Author/Contact Info bitshiftleft
Description: With better random number generators in the unix environments (/dev/random). I was looking for something like it on Win32, and there is. My motive is that I think some games that base there learning on neural nets may be learning on the poor periodic rand() type of random number generation. This means that the Neural Net may be learning the next roll of the dice rather than the game strategy itself. The Perl rand() repeats every 32000 times. Cryptographically generated random numbers gather entropy to seed there generators.
# -- csrand.pl - cryptographically secure random number generator
# -- For some reason the CAPICOM_ENCODE_BINARY option doesn't work in 
+the Activestate Win32 perl 5.8 implementation
# -- so I used CAPICOM_ENCODE_BASE64 and decoded that for the random n
+umber.
use Win32::OLE;
Win32::OLE->Option(Warn => 3);

# get CAPICOM VarType CONSTANTS from  Capicom.dll, commented out - tak
+es too long searching registry sometimes
#use Win32::OLE::Const 'CAPICOM v2.1 Type Library';
# --- use the constants below instead , thats all we need - get values
+ from object browser  
$CAPICOM_ENCODE_ANY = -1;
$CAPICOM_ENCODE_BASE64 = 0;
$CAPICOM_ENCODE_BINARY = 1;

my $RNG = Win32::OLE->new("CAPICOM.Utilities");  # download Capicom.dl
+l from Microsoft.com

my $die1 = 255; 
my $die2 = 255;
#--- for uniform distribution of die faces: 6 divides 252  252 = 251+1
+(includes zero)
while ($die1 > 251){ # reject if true - get another random number, mus
+t be divisible by 6 for uniformity
 $die1 = $RNG->GetRandom({Length => 1 , EncodingType => $CAPICOM_ENCOD
+E_BASE64}); # get one byte of random bits
 $die1 = unpack "C", DECODEBASE64($die1);
}
while ($die2 > 251){ # reject if true - get another random number, mus
+t be divisible by 6 for uniformity
 $die2 = $RNG->GetRandom({Length => 1 , EncodingType => $CAPICOM_ENCOD
+E_BASE64}); # get one byte of random bits
 $die2 = unpack "C", DECODEBASE64("$die2");
}

# --- the usual modulo 6 + 1 on an integer
print "You rolled ",$die1 % 6 + 1, ",",$die2 % 6 +1 ,"\n";

sub DECODEBASE64{  # see Programming Perl 2nd edition
my $die = $_[0];
$die =~ tr|A-Za-z0-9+/||cd;
$die =~ tr|A-Za-z0-9+/| -_|;
$die = unpack("u",pack("c", 32+(length $die)* .75) . $die);
return $die;
}
Replies are listed 'Best First'.
Re: A better rand() for Win32
by BrowserUk (Patriarch) on Jul 30, 2007 at 18:24 UTC
      Math::Random::MT is good choice - it uses Win32 Crypto API by using the Win32::API Module. Then to get a seed you start this in your code: use Math::Random::MT::Auto 'win32'; If you already have Math::Random::MT and Win32::API installed, use it. This offers an quick alternative for users who don't have or can't install Win32::API and Math::Random::MT and need only to install CAPICOM.dll that uses the same Crypto API.
      That smacks of a rhetorical question. (If it wasn't, please ignore the following.) Why do you think someone might want a short cut-and-paste solution over a CPAN module? (Look, another rhetorical question!) If you can come up with any answers, perhaps you might present them along with counter-arguments?

        Actually no. It wasn't rhetorical. I did a search for capicom, found a download page, attempted to follow the Capicom Reference link to find out what it was about. But, being MS, I got a "Sorry, there was a vowel in the month so we decided to change the location of everything on our website again, but oh dear, we seem to have missed updating a link", page. So, as I don't know if there is some advantage, and the docs do not appear to be available, I thought I would ask.

        And, in the event that the author was not familiar with Math::Random::MT, asking would bring that module to his attention also.

        Why do you think someone might want a short cut-and-paste solution over a CPAN module?

        If it were a simple C&P job, I might understand the motivation, but as you have to also download and install Capicom SDK, it doesn't seem any easier than installing the Math-Random PPD. Especially when it requires authentication which doesn't work for me, despite that I have all the appropriate Genuine Windows certificates of Authenticity, holograms, asset tags and product keys. Probably because I have configured my machine to disable a bunch of unnecessary services.

        As for counter arguments. It's hard to know what to counter until I know what advantages it is meant to have? Hence another reason for asking. I'm not at all convinced that entropy-based RNGs, especially those that require callouts to third-party websites, (I've failed to find out if capicom is one of these?), are much more secure than long period PRNGs like the Mersenne Twister, but I'm open to education on that.

        I am aware that it is necessary to seed the MT correctly in order to use it for cryptographic purposes, but that doesn't seem to be a consideration here.


        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.
      If you look at the paper describing the Mersenne Twister, one of the first sentences you can read in the FAQ is:
      Mersenne Twister is not cryptographically secure.
      Since this post here specifically mentions suitability for cryptographic purposes, at least, in its categorization, it should immediately be clear what its alleged advantage over Math::Random::MT is.
        Since this post here specifically mentions suitability for cryptographic purposes

        Read again.

        The only mention of 'cryptography' is the bland statement: " Cryptographically generated random numbers gather entropy to seed there generators." which is, by no reading that I can ascribe, the same as "suitability for cryptographic purposes".

        And, it might serve your purpose better to read an entire thread before going off half cocked.


        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.
Re: A better rand() for Win32
by pmonk4ever (Friar) on Sep 22, 2007 at 01:58 UTC
    Thanks for contributing an interesting piece of code to the Monastery Catacombs! I will enjoy taking it apart to analyze what makes it tick!!! Education is a wonderful thing...

    As for the discussion which ensued from the 1st post...I am a casual observer! It started getting deep for a while...but I persevered... I will say this, I am NOT a MS fan at all, and would NOT be willing to take a security hit for a PRNG!!! No matter HOW good it is!!!

    Thanks again...

    ki6jux

    ps...Why did you use a Perl reserved word "die" as a variable name???...

    "No trees were harmed in the creation of this node. However, a rather large number of electrons were somewhat inconvenienced."

      Die is singular to dice. When you roll one dice you are rolling one die !!! naturally it has nothing to do with the perl die function. It wasn't in mind when I coded it that way. I could have used $singledie instead of $die to avoid confusion.

      die

      Last time I looked there where no reserved variable names containing lower case letters in Perl.

        Ok, then I thought "die" was a reserved word, as in 'open <FILE> or die "you dummy! there is no file by that name: $FILE" '

        I am new at this, so please bear with me.

        Thank you.

        ki6jux

        "No trees were harmed in the creation of this node. However, a rather large number of electrons were somewhat inconvenienced."

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: sourcecode [id://629622]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (9)
As of 2024-03-28 11:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found