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.

164 Chapter 5 ■ Stream Ciphers and Block Ciphers

be combined with the counter using any invertible operation (XOR, addition,

or concatenation) to produce a unique counter block for encryption. If the IV

is not random, such as a packet counter, the IV and counter should be concatenated.

Figure 5.14 illustrates how the counter block is incremented during the

decryption process.

Nonce

c59bcf35...

Counter

00000000

Nonce

c59bcf35...

Counter

00000001

Nonce

c59bcf35...

Counter

00000002

Key

block cipher

encryption

Key

block cipher

encryption

Key

block cipher

encryption

Ciphertext

Ciphertextt

Ciphertext

Plaintext Plaintext Plaintext

Figure 5.14: Counter (CTR) mode decryption

Take caution with how you implement the counter; adding or XORing the

IV and counter into a single value could break the security under a chosenplaintext

attack; this is due to the attacker being able to manipulate the entire

IV–counter pair to cause a collision. Once an attacker controls the IV–counter

pair and plaintext, XOR of the ciphertext with the known plaintext would yield

a value that, when XOR’d with the ciphertext of the other block sharing the same

IV–counter pair, would decrypt that block. An example using the CTR mode

would look similar to the following:

from Crypto.Util import Counter

Counter.new(128, initial_value = int(binascii.hexlify('Not very

random.'), 16))

Tricks with Stream Modes

Notice that both the CTR and OFB modes act like stream ciphers (the “infinite

one-time pad” concept). That is, the block cipher is used to generate a sequence

of pseudorandom blocks that are XOR’d with the message. This ensures that

the message does not impact the random blocks.

These modes have some strengths and some weaknesses:

Strengths:

■■

The random stream can be precomputed on the encryption side

■■

We never have to decrypt a block cipher (so any one-way function can do

the job)

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

Saved successfully!

Ooh no, something went wrong!