Random data

Purpose

This class produces unpredictable, cryptographically secure random numbers. Using a predictable random number generator, such as System.Randomarrow-up-right, is insecure.

These functions should be used to randomly generate encryption keys, nonces, salts, seeds, integers, strings, and passphrases.

Usage

Fill

Fills a span with random bytes.

SecureRandom.Fill(Span<byte> buffer)

Exceptions

ArgumentOutOfRangeExceptionarrow-up-right

buffer has a length of 0.

GetInt32

Generates a random integer between 0 (inclusive) and the upper bound (exclusive).

SecureRandom.GetInt32(int upperBound)

Exceptions

ArgumentOutOfRangeExceptionarrow-up-right

upperBound is less than MinUpperBound.

GetString

Generates a random string of a given length. A custom character set can be provided, but several character sets are available via constants.

Exceptions

ArgumentOutOfRangeExceptionarrow-up-right

length is less than MinStringLength or greater than MaxStringLength.

ArgumentNullExceptionarrow-up-right

characterSet is null.

ArgumentOutOfRangeExceptionarrow-up-right

characterSet has a length of 0.

GetPassphrase

Generates a random passphrase using the EFF's long wordlistarrow-up-right (minus hyphenated words).

ArgumentOutOfRangeExceptionarrow-up-right

wordCount is less than MinWordCount or greater than MaxWordCount.

FillDeterministic

Fills a span with deterministic bytes indistinguishable from random without knowing the seed.

circle-exclamation

Exceptions

ArgumentOutOfRangeExceptionarrow-up-right

buffer has a length of 0.

ArgumentOutOfRangeExceptionarrow-up-right

seed has a length not equal to SeedSize.

Constants

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

Notes

triangle-exclamation
circle-info

The libsodium library uses RtlGenRandom() on Windows and getrandom or /dev/urandom on Linux and macOS to generate cryptographically secure random numbers non-deterministically. Deterministic generation is done using the IETF version of ChaCha20arrow-up-right.

Last updated