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 155

# generate a random key that has 32 bits

key = os.urandom(32)

print('The key that will be used is {}'.format(key))

print()

plaintext = b'Attack the yellow submarine.'

print('The plaintext is {}'.format(plaintext))

print()

# generate a random IV that has 12 bits

iv = os.urandom(12)

cip = ChaCha20Poly1305(key)

ciphertext = cip.encrypt(iv, plaintext)

print(ciphertext)

print()

plaintext = cip.decrypt(iv, ciphertext)

print(plaintext)

print()

The preceding use of the ChaCha20Poly1305 library should produce output

similar to Figure 5.4.

Figure 5.4: ChaCha20Poly1305

An alternative library that you may find helpful as well is the Crypto library.

You can import ChaCha20 from the Crypt.Cipher library:

import json

from base64 import b64encode

from Crypto.Cipher import ChaCha20

from Crypto.Random import get_random_bytes

plaintext = b'Attack at dawn'

key = get_random_bytes(32)

cipher = ChaCha20.new(key=key)

ciphertext = cipher.encrypt(plaintext)

nonce = b64encode(cipher.nonce).decode('utf-8')

ct = b64encode(ciphertext).decode('utf-8')

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

Saved successfully!

Ooh no, something went wrong!