07.07.2023 Views

Implementing-cryptography-using-python

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

116 Chapter 4 ■ Cryptographic Math and Frequency Analysis

Breaking C’s rand() Function

In the C programming language, and most other software languages, the

compiler implements pseudorandom number generators. Almost all module

functions depend on the basic function random(), which generates a random

float uniformly in the semi-open range [0.0, 1.0). Python uses the Mersenne

Twister algorithm as the core generator. It produces 53-bit precision floats and

has a period of 2**19937 − 1. The underlying implementation in C, the rand()

function, is both fast and thread safe. The Mersenne Twister is one of the most

extensively tested random number generators in existence. However, being

completely deterministic, it is not suitable for all purposes and is completely

unsuitable for cryptographic purposes. The random module also provides the

SystemRandom class, which uses the system function os.urandom() to generate

random numbers from sources provided by the operating system:

def crand(seed):

r=[]

r.append(seed)

for i in range(30):

r.append((16807*r[-1]) % 2147483647)

if r[-1] < 0:

r[-1] += 2147483647

for i in range(31, 34):

r.append(r[len(r)-31])

for i in range(34, 344):

r.append((r[len(r)-31] + r[len(r)-3]) % 2**32)

while True:

next = r[len(r)-31]+r[len(r)-3] % 2**32

r.append(next)

yield (next >> 1 if next < 2**32 else (next % 2**32) >> 1)

my_generator = crand(123)

for i in range(5):

print (next(my_generator))

The output for the program will match the “random” numbers produced

here. If the numbers are predictable, then they are not random:

128959393

1692901013

436085873

748533630

776550279

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!