silk.crypto.chacha20_poly1305.
Encrypt and authenticate data with ChaCha20-Poly1305, and encrypt with raw ChaCha20 (RFC 8439).
When to use#
Use ChaCha20Poly1305.seal to encrypt a message so that only holders of the key can read it
and any change is detected. Use ChaCha20Poly1305.open to check and decrypt it. It is fast
without AES hardware, and it is a cipher suite of TLS 1.3 and WireGuard.
Details#
The key is 32 bytes, the nonce is 12 bytes, and the tag is 16 bytes. The tag is separate from
the ciphertext ("detached"), so store or send both. The associated data (aad) is authenticated
but not encrypted. The ciphertext has the same length as the plaintext. Nothing allocates.
For data that arrives in parts, such as a Node.js createCipheriv("chacha20-poly1305") call,
use ChaCha20Poly1305Encryptor and ChaCha20Poly1305Decryptor. They take the message in
any split, give the same result, and can write or check a truncated tag of 1 to 16 bytes.
ChaCha20 is the raw stream cipher without authentication, for formats that name it.
ChaCha20 runs four blocks at a time in 128-bit vectors, and eight at a time with AVX2 when an x86-64 machine has it, checked at run time. Poly1305 keeps its accumulator in 64-bit words.
Errors#
The functions return an AeadError. All checks come before the first write, and on any error
the output buffers do not change. ChaCha20Poly1305.open writes no plaintext unless the tag
is correct.
Gotchas#
The same key and nonce must never encrypt two messages. If they do, an attacker can recover the
XOR of the two plaintexts and forge tags. Use a counter, or 12 random bytes from
silk.system.random for a small number of messages per key.
Authentication does not stop replay. The source code avoids branches on secret data, but the module cannot promise constant time on every compiler and target, or that secrets are erased.
Examples#
Encrypt, decrypt, and detect a change#
import silk.crypto.chacha20_poly1305 { AeadError, ChaCha20Poly1305 }
import silk.core.result { Result }
pub fn main() -> i32 {
let key: [u8; 32] = [42; 32]
let nonce: [u8; 12] = [0; 12]
let mut ciphertext: [u8; 5] = [0; 5]
let mut tag: [u8; 16] = [0; 16]
match ChaCha20Poly1305.seal(&key, &nonce, b"v1", b"hello", &mut ciphertext, &mut tag) {
Result<(), AeadError>.Success { value: _ } => {}
Result<(), AeadError>.Failure { error: _ } => {
return 1
}
}
let mut plaintext: [u8; 5] = [0; 5]
match ChaCha20Poly1305.open(&key, &nonce, b"v1", &ciphertext, &tag, &mut plaintext) {
Result<(), AeadError>.Success { value: _ } => {}
Result<(), AeadError>.Failure { error: _ } => {
return 1
}
}
if plaintext[0] != 104 || plaintext[4] != 111 {
return 1
}
// Other associated data gives a different tag, so open fails.
return match ChaCha20Poly1305.open(&key, &nonce, b"v2", &ciphertext, &tag, &mut plaintext) {
Result<(), AeadError>.Failure { error: AeadError.AuthenticationFailed } => 0
_ => 1
}
}Import as ChaCha20Poly1305 with import silk.crypto.chacha20_poly1305 { ChaCha20Poly1305 }.
Public declarations: 6.
AeadError#
pub enum AeadErrorThe reason that ChaCha20Poly1305.seal or ChaCha20Poly1305.open rejected a call. The
checks run in the order of the variants, and the first failure is returned.
InvalidKey#
InvalidKeyThe key is not 32 bytes.
InvalidNonce#
InvalidNonceThe nonce is not 12 bytes.
InvalidTag#
InvalidTagThe tag, or the tag output, is not 16 bytes.
OutputTooSmall#
OutputTooSmallThe output is shorter than the input message.
LimitExceeded#
LimitExceededThe message is longer than 274877906880 bytes (2^32 blocks of 64 bytes).
AuthenticationFailed#
AuthenticationFailedThe tag is not correct for the key, nonce, associated data, and ciphertext.
Implementation Debug for AeadError#
impl Debug for AeadErrorOperation debug#
effect fn debug(self: &Self, formatter: &mut Formatter) -> () ! WriterError ? &mut WriterWrites the name of the variant, such as InvalidKey.
ChaCha20Poly1305#
pub struct ChaCha20Poly1305Functions that encrypt and authenticate with ChaCha20-Poly1305 (RFC 8439).
When to use#
Use ChaCha20Poly1305.seal to encrypt a message so that only holders of the key can read it
and any change is detected. Use ChaCha20Poly1305.open to check and decrypt it. It is fast
without AES hardware, and it is a cipher suite of TLS 1.3 and WireGuard.
Details#
The key is 32 bytes, the nonce is 12 bytes, and the tag is 16 bytes. The tag is separate from the ciphertext, so store or send both. The ciphertext has the same length as the plaintext. Nothing allocates. All checks come before the first write, and on any error the output buffers do not change.
Gotchas#
The same key and nonce must never encrypt two messages. If they do, an attacker can recover the XOR of the two plaintexts and forge tags. Authentication does not stop replay. The source code avoids branches on secret data, but it cannot promise constant time on every compiler and target, or that secrets are erased.
Implementation ChaCha20Poly1305#
impl ChaCha20Poly1305Associated function seal#
pub fn seal(key: &[u8], nonce: &[u8], aad: &[u8], plaintext: &[u8], ciphertext: &mut [u8], tag: &mut [u8]) -> Result<(), AeadError>Encrypts plaintext into ciphertext and writes the 16-byte authentication tag to tag.
The key is 32 bytes and the nonce is 12 bytes. aad is authenticated but not encrypted. The
ciphertext has the same length as plaintext. ciphertext can be longer than plaintext.
The bytes after the written prefix do not change. Nothing allocates.
Errors#
All checks come before the first write. On an error, ciphertext and tag do not change.
The first failure in this order is returned:
InvalidKeyifkeyis not 32 bytes.InvalidNonceifnonceis not 12 bytes.InvalidTagiftagis not 16 bytes.OutputTooSmallifciphertextis shorter thanplaintext.LimitExceededifplaintextis longer than 274877906880 bytes (2^32 blocks of 64 bytes).
Gotchas#
Use a new nonce for each message under the same key. The function does not make one. If the
same key and nonce encrypt two messages, an attacker can recover the XOR of the two plaintexts
and forge tags. Use a counter, or 12 random bytes from silk.system.random for a small number
of messages per key.
Associated function open#
pub fn open(key: &[u8], nonce: &[u8], aad: &[u8], ciphertext: &[u8], tag: &[u8], plaintext: &mut [u8]) -> Result<(), AeadError>Checks tag, and if it is correct, decrypts ciphertext into plaintext.
aad must be the same bytes that were given to ChaCha20Poly1305.seal. The function checks
all 16 tag bytes before it writes plaintext. The bytes after the written prefix do not
change.
The key is 32 bytes, the nonce is 12 bytes, and the tag is 16 bytes. Nothing allocates.
Errors#
All checks come before the first write. On an error, plaintext does not change.
InvalidKeyifkeyis not 32 bytes.InvalidNonceifnonceis not 12 bytes.InvalidTagiftagis not 16 bytes.OutputTooSmallifplaintextis shorter thanciphertext.LimitExceededifciphertextis longer than 274877906880 bytes.AuthenticationFailedif the tag is not correct for the key, nonce,aad, and ciphertext.
Gotchas#
Authentication does not stop replay: an attacker can send an old valid message again.
ChaCha20Error#
pub enum ChaCha20ErrorThe reason that a ChaCha20 call was rejected.
InvalidKey#
InvalidKeyThe key is not 32 bytes.
InvalidNonce#
InvalidNonceThe nonce is not 12 bytes.
OutputTooSmall#
OutputTooSmallThe output is shorter than the input.
Implementation Debug for ChaCha20Error#
impl Debug for ChaCha20ErrorOperation debug#
effect fn debug(self: &Self, formatter: &mut Formatter) -> () ! WriterError ? &mut WriterWrites the name of the variant, such as InvalidKey.
ChaCha20#
pub struct ChaCha20A streaming ChaCha20 cipher (RFC 8439 section 2.4) without authentication.
When to use#
Use it only where a protocol names raw ChaCha20, such as Node's createCipheriv("chacha20").
It does not detect changes to the ciphertext. Use ChaCha20Poly1305 to encrypt messages.
Details#
The key is 32 bytes and the nonce is 12 bytes. counter is the number of the first 64-byte
block. Encryption and decryption are the same operation, so ChaCha20.apply does both, and
any split of the input gives the same output. After block 2^32 - 1 the counter carries into the
first nonce word, which is what OpenSSL does. Node's 16-byte chacha20 IV is the counter as a
little-endian u32 followed by the nonce. Nothing allocates.
Gotchas#
The same key, nonce and counter must never encrypt two messages. The value holds key material and is not erased when it is dropped.
Implementation ChaCha20#
impl ChaCha20Associated function make#
pub fn make(key: &[u8], nonce: &[u8], counter: u32) -> Result<ChaCha20, ChaCha20Error>Returns a cipher for key and nonce that starts at block counter.
Errors#
InvalidKeyifkeyis not 32 bytes.InvalidNonceifnonceis not 12 bytes.
Method apply#
pub fn apply(self: &mut Self, input: &[u8], output: &mut [u8]) -> Result<(), ChaCha20Error>XORs input with the key stream into the first input.length bytes of output.
The bytes of output after them do not change. The buffers must not overlap.
Errors#
OutputTooSmallifoutputis shorter thaninput. The state andoutputdo not change.
ChaCha20Poly1305Encryptor#
pub struct ChaCha20Poly1305EncryptorA streaming ChaCha20-Poly1305 encryptor (RFC 8439) for a message that arrives in parts.
When to use#
Use it when the message does not fit in one buffer, or to implement an API that encrypts in
steps, such as createCipheriv("chacha20-poly1305") in Node.js. For a message in one slice,
use ChaCha20Poly1305.seal.
Details#
Make one with ChaCha20Poly1305Encryptor.make and the associated data, give the message with
ChaCha20Poly1305Encryptor.update, then call ChaCha20Poly1305Encryptor.finish for the
tag. Any split of the message gives the same ciphertext and tag as ChaCha20Poly1305.seal.
Nothing allocates.
Gotchas#
The same key and nonce must never encrypt two messages. The value holds key material and is not erased when it is dropped.
Implementation ChaCha20Poly1305Encryptor#
impl ChaCha20Poly1305EncryptorAssociated function make#
pub fn make(key: &[u8], nonce: &[u8], aad: &[u8]) -> Result<ChaCha20Poly1305Encryptor, AeadError>Returns an encryptor for key and nonce that authenticates the associated data aad.
The encryptor copies what it needs and does not borrow the arguments.
Errors#
InvalidKeyifkeyis not 32 bytes.InvalidNonceifnonceis not 12 bytes.
Method update#
pub fn update(self: &mut Self, plaintext: &[u8], ciphertext: &mut [u8]) -> Result<(), AeadError>Encrypts plaintext into the first plaintext.length bytes of ciphertext.
The bytes of ciphertext after them do not change. The buffers must not overlap.
Errors#
On an error the state and ciphertext do not change.
OutputTooSmallifciphertextis shorter thanplaintext.LimitExceededif the message grows past 274877906880 bytes.
Method finish#
pub fn finish(self: Self, tag: &mut [u8]) -> Result<(), AeadError>Writes the authentication tag to tag and consumes the state.
tag is 16 bytes for the full tag, or 1 to 15 bytes for a prefix of it, as Node's
authTagLength allows. Shorter tags are easier to forge.
Errors#
InvalidTagiftagis empty or longer than 16 bytes.tagdoes not change.
ChaCha20Poly1305Decryptor#
pub struct ChaCha20Poly1305DecryptorA streaming ChaCha20-Poly1305 decryptor (RFC 8439) for a ciphertext that arrives in parts.
When to use#
Use it when the ciphertext does not fit in one buffer, or to implement an API that decrypts in
steps, such as createDecipheriv("chacha20-poly1305") in Node.js. For a ciphertext in one
slice, use ChaCha20Poly1305.open, which writes no plaintext unless the tag is correct.
Details#
Make one with ChaCha20Poly1305Decryptor.make and the associated data, give the ciphertext
with ChaCha20Poly1305Decryptor.update, then call ChaCha20Poly1305Decryptor.finish with
the received tag. Nothing allocates.
Gotchas#
ChaCha20Poly1305Decryptor.update writes plaintext before the tag is checked. Do not use or
release that plaintext until ChaCha20Poly1305Decryptor.finish succeeds. The value holds key
material and is not erased when it is dropped.
Implementation ChaCha20Poly1305Decryptor#
impl ChaCha20Poly1305DecryptorAssociated function make#
pub fn make(key: &[u8], nonce: &[u8], aad: &[u8]) -> Result<ChaCha20Poly1305Decryptor, AeadError>Returns a decryptor for key and nonce that authenticates the associated data aad.
aad must be the same bytes that the encryptor got. The decryptor copies what it needs and
does not borrow the arguments.
Errors#
InvalidKeyifkeyis not 32 bytes.InvalidNonceifnonceis not 12 bytes.
Method update#
pub fn update(self: &mut Self, ciphertext: &[u8], plaintext: &mut [u8]) -> Result<(), AeadError>Decrypts ciphertext into the first ciphertext.length bytes of plaintext.
The plaintext is not authenticated until ChaCha20Poly1305Decryptor.finish succeeds. The
bytes of plaintext after the written ones do not change. The buffers must not overlap.
Errors#
On an error the state and plaintext do not change.
OutputTooSmallifplaintextis shorter thanciphertext.LimitExceededif the ciphertext grows past 274877906880 bytes.
Method finish#
pub fn finish(self: Self, tag: &[u8]) -> Result<(), AeadError>Checks the received tag and consumes the state.
tag is the full 16-byte tag or a 1 to 15-byte prefix of it. The comparison takes the same
time wherever the bytes differ.
Errors#
InvalidTagiftagis empty or longer than 16 bytes.AuthenticationFailedif the tag is not correct for the key, nonce, associated data, and ciphertext. Discard all plaintext thatChaCha20Poly1305Decryptor.updatewrote.
Category: Cryptography.
Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2, x86_64-pc-windows-msvc, wasm64-unknown-unknown.