Dart Cryptography Insecure Random Key Generation

Description

This detector identifies cryptographic vulnerabilities where cryptographically weak random number generators are used for key generation. Using dart:math Random class for cryptographic keys creates predictable values that can be exploited by attackers to compromise encryption security.

Weakness:

034 - Insecure generation of random numbers

Category: Probabilistic Techniques

Detection Strategy

    The code must import both the 'package:cryptography' library and 'dart:math' library to indicate cryptographic operations with potential random number usage

    The file being analyzed must not be a test file (test files are excluded from this security check)

    The detector examines method calls and function invocations that have arguments sourced from random number generation

    A vulnerability is reported when a cryptographic function receives an argument that traces back to dart:math Random class instead of cryptographically secure random sources

    The random value must flow from its generation point through the code to reach a cryptographic function parameter to trigger detection

Vulnerable code example

import 'dart:math';
import 'package:cryptography/cryptography.dart';

// VULNERABLE: Using non-CSPRNG Random() for cryptographic nonce generation
Future<void> insecureEncryption(List<int> msg, SecretKey k) async {
  final aesGcm = AesGcm.with256bits();
  final nonceBytes = List<int>.generate(12, (_) => Random().nextInt(256)); // Random() is not cryptographically secure
  await aesGcm.encrypt(msg, secretKey: k, nonce: nonceBytes);...

✅ Secure code example

import 'dart:math';
import 'package:cryptography/cryptography.dart';

// SECURE: Using Random.secure() CSPRNG for cryptographic nonce generation
Future<void> secureEncryption(List<int> msg, SecretKey k) async {
  final aesGcm = AesGcm.with256bits();
  final nonceBytes = List<int>.generate(12, (_) => Random.secure().nextInt(256)); // Random.secure() is cryptographically secure
  await aesGcm.encrypt(msg, secretKey: k, nonce: nonceBytes);...