ChaCha20-Poly1305

Purpose

ChaCha20-Poly1305 is an authenticated encryption with associated data (AEAD) scheme. It encrypts a plaintext message using a 256-bit key and 96-bit nonce (number used only once) before computing a tag over the ciphertext and associated data.

The associated data is useful for authenticating file headers, version numbers, timestamps, counters, and so on. It can be used to prevent confused deputy attacks and replay attacks. It is not encrypted nor part of the ciphertext. It must be reproduceable or stored somewhere for decryption to be possible.

For decryption, the tag is first verified for the given inputs, which detects tampering and incorrect parameters. If verification fails, an error is returned. Otherwise, the ciphertext is decrypted and plaintext is returned.

Usage

Encrypt

Fills a span with ciphertext and an appended tag computed from a plaintext message, nonce, key, and optional associated data.

ChaCha20Poly1305.Encrypt(Span<byte> ciphertext, ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> key, ReadOnlySpan<byte> associatedData = default)

Exceptions

ArgumentOutOfRangeException

ciphertext has a length not equal to plaintext.Length + TagSize.

ArgumentOutOfRangeException

nonce has a length not equal to NonceSize.

ArgumentOutOfRangeException

key has a length not equal to KeySize.

CryptographicException

Encryption failed.

Decrypt

Verifies that the tag appended to the ciphertext is correct for the given inputs. If verification fails, an exception is thrown. Otherwise, it fills a span with the decrypted ciphertext.

ChaCha20Poly1305.Decrypt(Span<byte> plaintext, ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> key, ReadOnlySpan<byte> associatedData = default)

Exceptions

ArgumentOutOfRangeException

plaintext has a length not equal to ciphertext.Length - TagSize.

ArgumentOutOfRangeException

ciphertext has a length less than TagSize.

ArgumentOutOfRangeException

nonce has a length not equal to NonceSize.

ArgumentOutOfRangeException

key has a length not equal to KeySize.

CryptographicException

Invalid authentication tag for the given inputs.

Constants

These are used for validation and/or save you defining your own constants.

public const int KeySize = 32;
public const int NonceSize = 12;
public const int TagSize = 16;

Notes

Last updated