ChaCha20

ChaCha20 is a stream cipher designed by Daniel J. Bernstein. The secret key is 256 bits long.

This is an example of how ChaCha20 can encrypt data:

>>> from Crypto.Cipher import ChaCha20
>>>
>>> plaintext = b'Attack at dawn'
>>> secret = b'*Thirty-two byte (256 bits) key*'
>>> cipher = ChaCha20.new(key=secret)
>>> msg = cipher.nonce + cipher.encrypt(plaintext)

And this is how you would decrypt it:

>>> from Crypto.Cipher import ChaCha20
>>>
>>> secret = b'*Thirty-two byte (256 bits) key*'
>>> msg_nonce = msg[:8]
>>> ciphertext = msg[8:]
>>> cipher = ChaCha20.new(key=secret, nonce=msg_nonce)
>>> plaintext = cipher.decrypt(ciphertext)

Warning

ChaCha20 does not guarantee authenticity of the data you decrypt! In other words, an attacker may manipulate the data in transit. In order to prevent it, you must couple it with a Message Authentication Code (such as HMAC).

class Crypto.Cipher.ChaCha20.ChaCha20Cipher(key, nonce)

ChaCha20 cipher object. Do not create it directly. Use new() instead.

Variables:nonce (byte string) – The nonce with length 8
decrypt(ciphertext)

Decrypt a piece of data.

Parameters:ciphertext (byte string) – The data to decrypt, of any size.
Returns:the decrypted byte string, of equal length as the ciphertext.
encrypt(plaintext)

Encrypt a piece of data.

Parameters:plaintext (byte string) – The data to encrypt, of any size.
Returns:the encrypted byte string, of equal length as the plaintext.
seek(position)

Seek to a certain position in the key stream.

Parameters:position (integer) – The absolute position within the key stream, in bytes.
Crypto.Cipher.ChaCha20.new(**kwargs)

Create a new ChaCha20 cipher

Keyword Arguments:
 
  • key – The secret key to use. It must be 32 bytes long.
  • nonce

    A mandatory value that must never be reused for any other encryption done with this key. It must be 8 bytes long.

    If not provided, a random byte string will be generated (you can read it back via the nonce attribute of the returned object).

Return:

a Crypto.Cipher.ChaCha20.ChaCha20Cipher object