Crate rand_chacha

Source
Expand description

The ChaCha random number generators.

These are native Rust implementations of RNGs derived from the ChaCha stream ciphers by D J Bernstein.

§Generators

This crate provides 8-, 12- and 20-round variants of generators via a “core” implementation (of BlockRngCore), each with an associated “RNG” type (implementing RngCore).

These generators are all deterministic and portable (see Reproducibility in the book), with testing against reference vectors.

§Cryptographic (secure) usage

Where secure unpredictable generators are required, it is suggested to use ChaCha12Rng or ChaCha20Rng and to seed via SeedableRng::from_os_rng.

See also the Security chapter in the rand book. The crate is provided “as is”, without any form of guarantee, and without a security audit.

§Seeding (construction)

Generators implement the SeedableRng trait. Any method may be used, but note that seed_from_u64 is not suitable for usage where security is important. Some suggestions:

  1. With a fresh seed, direct from the OS (implies a syscall):
    let rng = ChaCha12Rng::from_os_rng();
  2. From a master generator. This could be rand::rng (effectively a fresh seed without the need for a syscall on each usage) or a deterministic generator such as ChaCha20Rng. Beware that should a weak master generator be used, correlations may be detectable between the outputs of its child generators.
    let rng = ChaCha12Rng::from_rng(&mut rand::rng());

See also Seeding RNGs in the book.

§Generation

Generators implement RngCore, whose methods may be used directly to generate unbounded integer or byte values.

use rand_core::{SeedableRng, RngCore};
use rand_chacha::ChaCha12Rng;

let mut rng = ChaCha12Rng::from_seed(Default::default());
let x = rng.next_u64();
assert_eq!(x, 0x53f955076a9af49b);

It is often more convenient to use the rand::Rng trait, which provides further functionality. See also the Random Values chapter in the book.

Re-exports§

Structs§

  • ChaCha with 8 rounds
  • A cryptographically secure random number generator that uses the ChaCha algorithm.
  • ChaCha with 12 rounds
  • A cryptographically secure random number generator that uses the ChaCha algorithm.
  • ChaCha with 20 rounds
  • A cryptographically secure random number generator that uses the ChaCha algorithm.

Type Aliases§