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 147

at the first register. The output of register 1 is the XOR of bit 66 (1) and bit 93

(0), which is 1. Register 2’s output is bit 162 XOR bit 177, which is also 1. Finally,

register 3 is the XOR of bit 288 (1) and bit 243 (0), so also a 1. Thus, the first

output is 1. Now everything must slide, so let’s look at the feedback. The input

to register 2 is the XOR of bit 171 (1) and the XOR of that first register’s output

bit (1) and the product of bits 91 and 92 (0), so 1 + 1 + 0 = 0 is the new input bit

to register 2. All the other bits in register 2 slide one to the right. (Register 2 is

now 0 in bit 94, 1 in bits 95−174, and 0 everywhere else.) Likewise, you can trace

that the new input bit of register 3 is a 1. The new input bit for register 1 is a 0.

Now that we have introduced stream ciphers, you can examine some additional

stream ciphers, namely, ARC4, Vernam, Salsa20, and the ChaCha20 ciphers.

Both the Salsa20 and the ChaCha20 are similar in nature as they were created

by the same author.

ARC4

The RC4 stream cipher was created by Ron Rivest in 1987. RC4 was classified as

a trade secret by RSA Security but was eventually leaked to a message board

in 1994. RC4 was originally trademarked by RSA Security so it is often referred

to as ARCFOUR or ARC4 to avoid trademark issues. ARC4 would later become

commonly used in a number of encryption protocols and standards such as SSL,

TLS, WEP, and WPA. In 2015, it was prohibited for all versions of TLS by RFC

7465. ARC4 has been used in many hardware and software implementations.

One of the main advantages of ARC4 is its speed and simplicity, which you will

notice in the following code:

"""

Implement the ARC4 stream cipher. - Chapter 5

"""

def arc4crypt(data, key):

x = 0

box = range(256)

for i in range(256):

x = (x + box[i] + ord(key[i % len(key)])) % 256

# swap range objects

box = list(box)

box[i], box[x] = box[x], box[i]

x = 0

y = 0

out = []

for char in data:

x = (x + 1) % 256

y = (y + box[x]) % 256

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

Saved successfully!

Ooh no, something went wrong!