07.07.2023 Views

Implementing-cryptography-using-python

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

142 Chapter 5 ■ Stream Ciphers and Block Ciphers

experiment to gain an understanding of the underlying mechanics. Once you

complete it, you should feel comfortable with the use of XOR, seeds, and the

general structure of a stream cipher. This section builds the base in which we

add improvements with true security in mind.

In building your first stream cipher, you take the idea of the one-time pad

mixed with the convenience of PRGNs to create an encryption scheme. Since

we haven’t explored any nonbreakable PRNGs yet, we will work with an insecure

one, but the mechanics are identical when you have a more secure source

of pseudorandom bits. It is important to know that since you want to use the

stream cipher to work on real-world data, it is going to have to encrypt ASCII

characters, which means you need to think about the use of random bytes more

than the use of random bits. It is not much of a change, but it is worth mentioning.

To start, we select the C rand() function as our PRNG since we have code for

it from Chapter 4. It generates 31 bits at a time (the numbers are mod 2 31 ), and

you want 8 bits at a time. For the sake of this example, use the lowest 24 bits of

each number that comes out and generate three bytes of randomness for our

stream. Using these guidelines, this should allow you to generate a convention

that matches the partner with which you are communicating. A rand()-generated

number might look like temp = 2158094741372. If you want three bytes of randomness

from that, you could follow these steps:

>>> temp = 2158094741372

>>> temp % 2**8

124

>>> (temp >> 8) % 2**8

111

>>> (temp >> 16) % 2**8

120

The code should produce three numbers uniformly chosen between 0 and

255. Now let’s write our own simple PRNG function. It should produce four

output numbers, [1471611625, 1204518815, 463882823, 963005816]:

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

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

Saved successfully!

Ooh no, something went wrong!