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.

Chapter 5 ■ Stream Ciphers and Block Ciphers 141

contain an even number of hexadecimal digits. Since the output of the hexlify

function returns twice the length, unhexlify returns half the length. Here’s

an example of using unhexlify to convert back to binary from hexadecimal:

>>> unpasshex = binascii.unhexlify(passhex)

>>> unpasshex

b'apples are red'

Furthermore, Python allows you to use an x escape character to convert from

hexadecimal back to plaintext, as shown here:

>>> hx = '\x61'

>>> hx

'a'

Use Stream Ciphers

Let’s now start exploring private-key cryptography by looking at what stream

ciphers are and then examine them as a combination of the one-time pad (OTP)

and cryptographically secure pseudorandom number generators (CSPRNGs).

The concepts of the OTP that make it perfectly secure are what you capitalize

on to make a more robust cipher. As you may recall from Chapter 2, the onetime

pad takes a message of n bits and a uniformly random secret key of the

same length and generates a ciphertext by bitwise XOR. The encryption and

decryption methods are identical operations.

When you examine the elegance of the OTP, you will undoubtedly see its

weaknesses as well:

■■

You must arrange a key exchange between the sender and receiver of the

message; this is true in all symmetric schemes.

■■

You can use the key only once.

■■

The key length is equal to the message length; if you have a way to send

the key securely, then perhaps you could have just sent the message.

You could resolve one of the most significant OTP problems if both parties

could generate keys on the fly with the other party. Ideally, both parties would

use an unpredictable pseudorandom number generator that would start from

the same seed and generate a uniformly random stream of noise that acts like

the one-time pad key. As you witnessed in the previous chapter, PRNGs can

be predictable and therefore can be cracked. Thus, we need to find improved

cryptographically secure pseudorandom number generators.

The goal of this section is to guide you through the creation of your first

“do it yourself” stream cipher. We will utilize an insecure stream cipher as an

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

Saved successfully!

Ooh no, something went wrong!