For AI agents: A markdown version of this page is available at https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/dart-security/weak-random.md. A documentation index is available at /llms.txt.

Use cryptographically secure random number generator

This product is not supported for your selected Datadog site. ().

Metadata

ID: dart-security/weak-random

Language: Dart

Severity: Warning

Category: Security

CWE: 338

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

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

import 'dart:math';

void main() {
  final rng = Random.secure();
  final token = rng.nextInt(1 << 32).toRadixString(16);
  print(token);
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security