Crate spinoso_securerandom

source ·
Expand description

Secure random number generator interface.

This module implements the SecureRandom package from the Ruby Standard Library. It is an interface to secure random number generators which are suitable for generating session keys in HTTP cookies, etc.

This implementation of SecureRandom supports the system RNG via the getrandom crate. This implementation does not depend on OpenSSL.


Generate cryptographically secure random bytes:

let bytes = spinoso_securerandom::random_bytes(Some(1024))?;
assert_eq!(bytes.len(), 1024);

Generate base64-encoded random data:

let bytes = spinoso_securerandom::base64(Some(1024))?;
assert_eq!(bytes.len(), 1368);

Generate random floats and integers in a range bounded from zero to a maximum:

let rand = spinoso_securerandom::random_number(Max::None)?;
assert!(matches!(rand, Rand::Float(_)));

let rand = spinoso_securerandom::random_number(Max::Integer(57))?;
assert!(matches!(rand, Rand::Integer(_)));

let rand = spinoso_securerandom::random_number(Max::Float(57.0))?;
assert!(matches!(rand, Rand::Float(_)));

Generate version 4 random UUIDs:

let uuid = spinoso_securerandom::uuid()?;
assert_eq!(uuid.len(), 36);
assert!(uuid.chars().all(|ch| ch == '-' || ch.is_ascii_hexdigit()));


  • Error that indicates an argument parsing or value logic error occurred.
  • Error that indicates the given maximum value is not finite and cannot be used to bound a domain for generating random numbers.
  • Error that indicates the underlying source of randomness failed to generate the requested random bytes.
  • A handle to the underlying secure random number generator.


  • Sum type of all errors possibly returned from random_bytes.
  • Max value when generating a random number from a range.
  • Random numeric value generated from the secure random number generator.