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.
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);...Search for vulnerabilities in your apps for free with Fluid Attacks' automated security testing! Start your 21-day free trial and discover the benefits of the Continuous Hacking Essential plan. If you prefer the Advanced plan, which includes the expertise of Fluid Attacks' hacking team, fill out this contact form.