Dart Cryptography Hardcoded Nonce
Description
This detector identifies hardcoded cryptographic nonces in Dart applications using the cryptography package. Hardcoded nonces are a serious security vulnerability because nonces must be unique and unpredictable for each encryption operation - reusing the same nonce with the same key can allow attackers to decrypt data or forge messages.
Detection Strategy
• The code must import or reference the 'package:cryptography' library
• The detector identifies calls to SecretBox constructor or methods from predefined nonce-related method sinks
• It examines the arguments passed to these cryptographic functions
• A vulnerability is reported when a hardcoded literal value (string, number, or static value) is found as an argument where a nonce parameter is expected
• The detector specifically looks for non-random, static values that would be reused across encryption operations
Vulnerable code example
import 'package:cryptography/cryptography.dart';
// VULNERABLE: Using hardcoded nonce breaks AEAD security
Future<void> encryptWithFixedNonce() async {
final aesGcm = AesGcm.with256bits();
final k = await aesGcm.newSecretKey();
final msg = <int>[1, 2, 3];
final box = await aesGcm.encrypt(msg, secretKey: k, nonce: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); // Reused nonce compromises confidentiality...✅ Secure code example
import 'package:cryptography/cryptography.dart';
// SAFE: Let AES-GCM auto-generate a secure nonce
Future<void> encryptWithSecureNonce() async {
final aesGcm = AesGcm.with256bits();
final k = await aesGcm.newSecretKey();
final msg = <int>[1, 2, 3];
final box = await aesGcm.encrypt(msg, secretKey: k); // Omitting nonce: lets cryptography generate a CSPRNG nonce...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.