This is a python implementation of the excellently named “Blum Blum Shub” algorithm for generating pseudorandom numbers. See the wikipedia article for more information. This algorithm is good for use in cryptography, but due to its relatively slow speed, its not ideal for simulations.
The primes code came from www.4dsolutions.net/. I’m honestly not sure what the licence for that code is so the best I can do is to credit the site and thank them for the excellent resources they put online!
"""
Adapted from http://javarng.googlecode.com/svn/trunk/com/modp/random/BlumBlumShub.java
Original license follows:-
Copyright 2005, Nick Galbreath -- nickg [at] modp [dot] com
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Neither the name of the modp.com nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This is the standard "new" BSD license:
http://www.opensource.org/licenses/bsd-license.php
"""
import primes;
import random;
import sys;
class BlumBlumShub(object):
def getPrime(self, bits):
"""
Generate appropriate prime number for use in Blum-Blum-Shub.
This generates the appropriate primes (p = 3 mod 4) needed to compute the
"n-value" for Blum-Blum-Shub.
bits - Number of bits in prime
"""
while True:
p = primes.bigppr(bits);
if p%4 == 3:
break
return p
def generateN(self, bits):
"""
This generates the "n value" for use in the Blum-Blum-Shub algorithm.
bits - The number of bits of security
"""
p = self.getPrime(bits/2)
q = self.getPrime(bits/2)
# make sure p != q (almost always true, but just in case, check)
while p == q:
q = getPrime(self, bits/2);
# print "GenerateN - p = " + repr(p) + ", q = " + repr(q)
return p * q;
def __init__(self, bits):
"""
Constructor, specifing bits for n.
bits - number of bits
"""
self.n = self.generateN(bits)
# print "n set to " + repr(self.n)
length = self.bitLen(self.n)
seed = random.getrandbits(length)
self.setSeed(seed)
def setSeed(self, seed):
"""
Sets or resets the seed value and internal state.
seed -The new seed
"""
self.state = seed % self.n
def bitLen(self, x):
" Get the bit lengh of a positive number"
assert(x>0)
q = 0
while x:
q = q+1
x = x>>1
return q
def next(self, numBits):
"Returns up to numBit random bits"
result = 0
for i in range(numBits,0,-1):
self.state = (self.state**2) % self.n
result = (result << 1) | (self.state&1)
return result
def main():
bbs = BlumBlumShub(128);
#print "Generating 10 numbers"
print "type: u"
print "numbit: 32"
print "count: 5000000"
for i in range (0,5000000):
print bbs.next(32)
if __name__ == "__main__":
main()
"""
From http://www.4dsolutions.net/cgi-bin/py2html.cgi?script=/ocn/python/primes.py
"""
import random
def bigppr(bits=256):
"""
Randomly generate a probable prime with a given
number of hex digits
"""
candidate = random.getrandbits(bits)
if candidate&1==0:
candidate += 1
prob = 0
while 1:
prob=pptest(candidate)
if prob>0: break
else: candidate += 2
return candidate
def pptest(n):
"""
Simple implementation of Miller-Rabin test for
determining probable primehood.
"""
bases = [random.randrange(2,50000) for x in range(90)]
# if any of the primes is a factor, we're done
if n<=1: return 0
for b in bases:
if n%b==0: return 0
tests,s = 0L,0
m = n-1
# turning (n-1) into (2**s) * m
while not m&1: # while m is even
m >>= 1
s += 1
for b in bases:
tests += 1
isprob = algP(m,s,b,n)
if not isprob: break
if isprob: return (1-(1./(4**tests)))
else: return 0
def algP(m,s,b,n):
"""
based on Algorithm P in Donald Knuth's 'Art of
Computer Programming' v.2 pg. 395
"""
result = 0
y = pow(b,m,n)
for j in range(s):
if (y==1 and j==0) or (y==n-1):
result = 1
break
y = pow(y,2,n)
return result
