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.

152 Chapter 5 ■ Stream Ciphers and Block Ciphers

same operation on multiple data points simultaneously. Most modern-day CPU

designs include SIMD instruction to improve the performance of multimedia.

The second difference is that ChaCha builds the initial matrix with all attackercontrolled

input words at the bottom:

Constant Constant Constant Constant

Key Key Key Key

Key Key Key Key

Input Input Input Input

These constants are the same as in Salsa20. The first round of ChaCha adds

keys into the constants. The key words are copied in order; the input words are

the block counter followed by the nonce.

The third difference is that ChaCha processes through rows in the same order

in every round. The first round modifies first, fourth, third, second, first, fourth,

third, second along columns, and the second round modifies first, fourth, third,

second, first, fourth, third, second along southeast diagonals:

quarter_round (x0,x4,x8,x12)

quarter_round (x1,x5,x9,x13)

quarter_round (x2,x6,x10,x14)

quarter_round (x3,x7,x11,x15)

quarter_round (x0,x5,x10,x15)

quarter_round (x1,x6,x11,x12)

quarter_round (x2,x7,x8,x13)

quarter_round (x3,x4,x9,x14)

The four quarter-round words are always in top-to-bottom order in the matrix.

A couple libraries are available that will offer ChaCha as an encryption scheme.

You may also elect to use a pure Python implementation. To implement ChaCha

using Python, use the following recipe:

"""

Implement the ChaCha20 stream cipher.

"""

import struct

import sys, os, binascii

from base64 import b64encode

def yield_chacha20_xor_stream(key, iv, position=0):

# Generate the xor stream with the ChaCha20 cipher."""

if not isinstance(position, int):

raise TypeError

if position & ~0xffffffff:

raise ValueError('Position is not uint32.')

if not isinstance(key, bytes):

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

Saved successfully!

Ooh no, something went wrong!