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/hardcoded-encryption-key.md. A documentation index is available at /llms.txt.

Avoid deriving cryptographic keys from hardcoded strings

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

Metadata

ID: dart-security/hardcoded-encryption-key

Language: Dart

Severity: Error

Category: Security

CWE: 321

Description

Deriving an encryption key or IV from a hardcoded string literal (for example Key.fromUtf8 or IV.fromBase64) lets anyone who reads the source or binary recover the key and decrypt the data it protects, and it cannot be rotated without shipping new code. A hardcoded IV is equally unsafe, since reusing a fixed IV weakens modes such as CBC, CTR, and GCM.

Derive keys at runtime from a key derivation function or load them from secure storage, and use a unique random IV for every operation.

Non-Compliant Code Examples

import 'package:encrypt/encrypt.dart';
import 'package:encrypt/encrypt.dart' as encrypt;

Key utf8Key() {
  return Key.fromUtf8('my 32 length key1234567890123456');
}

Key base16Key() {
  return Key.fromBase16('0123456789abcdef0123456789abcdef');
}

IV utf8Iv() {
  return IV.fromUtf8('1234567890123456');
}

Key prefixedKey() {
  return encrypt.Key.fromUtf8('0123456789abcdef0123456789abcdef');
}

Compliant Code Examples

import 'package:encrypt/encrypt.dart';
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:flutter_dotenv/flutter_dotenv.dart';

Key secureRandomKey() {
  return Key.fromSecureRandom(32);
}

Key prefixedSecureKey() {
  return encrypt.Key.fromSecureRandom(32);
}

IV randomIv() {
  return IV.fromSecureRandom(16);
}

IV ivFromLength() {
  return IV.fromLength(16);
}
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