Expand description
IETF ChaCha20 as specified in the RFC 8439.
Parameters:
secret_key
: The secret key.nonce
: The nonce value.initial_counter
: The initial counter value. In most cases this is0
.ciphertext
: The encrypted data.plaintext
: The data to be encrypted.dst_out
: Destination array that will hold the ciphertext/plaintext after encryption/decryption.
nonce
: “Counters and LFSRs are both acceptable ways of generating unique nonces, as is
encrypting a counter using a block cipher with a 64-bit block size
such as DES. Note that it is not acceptable to use a truncation of a
counter encrypted with block ciphers with 128-bit or 256-bit blocks,
because such a truncation may repeat after a short time.” See RFC
for more information.
Exceptions:
An exception will be thrown if:
slice
when callingSecretKey::from_slice()
is not 32 bytes.- The
OsRng
fails to initialize or read from its source when callingSecretKey::generate()
. - The length of
dst_out
is less thanplaintext
orciphertext
. plaintext
orciphertext
are empty.plaintext
orciphertext
are longer than (2^32)-2.- The
initial_counter
is high enough to cause a potential overflow.
Even though dst_out
is allowed to be of greater length than plaintext
, the ciphertext
produced by chacha20
/xchacha20
will always be of the same length as the plaintext
.
Note:
keystream_block
is for use-cases where more control over the keystream used for
encryption/decryption is desired. It does not encrypt anything. This function’s counter
parameter is never increased
and therefor is not checked for potential overflow on increase either.
Only use it if you are absolutely sure you actually need to use it.
Security:
- It is critical for security that a given nonce is not re-used with a given key. Should this happen, the security of all data that has been encrypted with that given key is compromised.
- Functions herein do not provide any data integrity. If you need
data integrity, which is nearly always the case, you should use an AEAD construction instead.
See orions
aead
module for this. - Only a nonce for XChaCha20 is big enough to be randomly generated using a CSPRNG.
- To securely generate a strong key, use
SecretKey::generate()
.
Recommendation:
- It is recommended to use XChaCha20Poly1305 when possible.
Example:
use orion::hazardous::stream::chacha20;
let secret_key = chacha20::SecretKey::generate().unwrap();
let nonce = chacha20::Nonce::from_slice(&[
0x07, 0x00, 0x00, 0x00, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
]).unwrap();
// Length of this message is 15
let message = "Data to protect".as_bytes();
let mut dst_out_pt = [0u8; 15];
let mut dst_out_ct = [0u8; 15];
chacha20::encrypt(&secret_key, &nonce, 0, message, &mut dst_out_ct);
chacha20::decrypt(&secret_key, &nonce, 0, &dst_out_ct, &mut dst_out_pt);
assert_eq!(dst_out_pt, message);
Structs
Nonce
that ChaCha20 and ChaCha20Poly1305 use.SecretKey
that chacha20
, xchacha20
, chacha20poly1305
and
xchacha20poly1305
use.