---
title: Avoid deriving cryptographic keys from hardcoded strings
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Avoid deriving cryptographic keys from hardcoded strings
---

> For the complete documentation index, see [llms.txt](https://docs.datadoghq.com/llms.txt).

# Avoid deriving cryptographic keys from hardcoded strings

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com, us2.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site.md). ({% placeholder "user-datadog-site-name" /%}).
{% /alert %}

{% /callout %}

## Metadata{% #metadata %}

**ID:** `dart-security/hardcoded-encryption-key`

**Language:** Dart

**Severity:** Error

**Category:** Security

**CWE**: [321](https://cwe.mitre.org/data/definitions/321.html)

## Description{% #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{% #non-compliant-code-examples %}

```dart
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{% #compliant-code-examples %}

```dart
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);
}
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 