---
title: Use a cryptographically secure RNG
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Use a cryptographically secure RNG
---

# Use a cryptographically secure RNG

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com, us2.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site.md). ({% placeholder "user-datadog-site-name" /%}).
{% /alert %}

{% /callout %}

## Metadata{% #metadata %}

**ID:** `rust-security/insecure-random`

**Language:** Rust

**Severity:** Warning

**Category:** Security

**CWE**: [338](https://cwe.mitre.org/data/definitions/338.html)

## Description{% #description %}

Several pseudo-random number generators (PRNGs) in the Rust ecosystem are explicitly not cryptographically secure. Unlike a CSPRNG, their internal state can be recovered by observing a small number of outputs, making them unsuitable in security-sensitive contexts such as generating authentication tokens, API keys, or cryptographic keys.

This rule flags uses of `SmallRng`, the companion crates `rand_pcg`, `rand_xoshiro`, `rand_xorshift`, and `rand_isaac`, the third-party crates `fastrand`, `nanorand`, and `oorandom`.

Use `rand::random()`, `rand::rng()`, `StdRng::from_entropy()`, or `OsRng` instead.

## Non-Compliant Code Examples{% #non-compliant-code-examples %}

```rust
use rand::rngs::SmallRng;
use rand_pcg::Pcg32;
use rand_xoshiro::Xoshiro256PlusPlus;
use rand::SeedableRng;
use rand::rngs::StdRng;

fn small_rng_uses() {
    let _ = SmallRng::from_entropy();
    let _ = SmallRng::seed_from_u64(0);
}

fn fully_qualified() {
    let _ = rand_pcg::Pcg32::new(0, 0);
    let _ = fastrand::u32(0..100);
}
```

## Compliant Code Examples{% #compliant-code-examples %}

```rust
use rand::random;
use rand::Rng;
use rand::rngs::OsRng;
use rand::rngs::StdRng;
use rand::SeedableRng;
use rand_chacha::ChaCha20Rng;

fn ok_calls() {
    let _: u32 = rand::random();
    let _: u32 = rand::rng().gen();
    let _: u32 = rand::thread_rng().gen();
    let _ = StdRng::from_entropy();
    let _ = ChaCha20Rng::from_entropy();
    let mut buf = [0u8; 32];
    OsRng.fill(&mut buf);
}
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 