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

> For the complete documentation index, see [llms.txt](https://docs.datadoghq.com/llms.txt).

# Use cryptographically secure random number generator

{% 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:** `dart-security/weak-random`

**Language:** Dart

**Severity:** Warning

**Category:** Security

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

## Description{% #description %}

`dart:math Random()` produces pseudorandom sequences from a deterministic seed and is not suitable for security-sensitive operations. Using it for session tokens, API keys, cryptographic nonces, or other secrets can expose your application to prediction and replay attacks.

Replace `Random()` with `Random.secure()`, which draws entropy from the platform OS CSPRNG and is safe for all security-critical randomness needs including key generation and token creation.

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

```dart
import 'dart:math';

String generateToken() {
  final rng = Random();
  return rng.nextInt(1 << 32).toRadixString(16);
}

String generateApiKey() {
  final rng = Random(42);
  return List.generate(16, (_) => rng.nextInt(256).toRadixString(16).padLeft(2, '0')).join();
}
```

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

```dart
import 'dart:math';

void main() {
  final rng = Random.secure();
  final token = rng.nextInt(1 << 32).toRadixString(16);
  print(token);
}
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 