logo

Database

C Sharp Hardcoded Algorithm Key

Description

This detector identifies hardcoded cryptographic keys in C# code that uses the `System.Security.Cryptography` namespace. Embedding cryptographic keys directly in source code is a critical security vulnerability because it exposes the keys to anyone with access to the codebase, making encryption trivially bypassable and preventing secure key rotation without code changes.

Weakness:

009 - Sensitive information in source code

Category: Information Collection

Detection Strategy

    • The detector only activates when the `System.Security.Cryptography` namespace is explicitly imported in the file being analyzed, ensuring the check is scoped to code that performs cryptographic operations.

    • Each selected code location is individually evaluated by the `_is_vulnerable` function to determine whether it represents a hardcoded key being passed to or used within a cryptographic algorithm context (e.g., directly supplying a literal byte array or string as a key to a symmetric or asymmetric cipher).

    • A vulnerability is reported for every code location where a cryptographic key value is determined to be hardcoded (i.e., defined as a constant or literal) rather than being dynamically retrieved from a secure source such as a key vault, environment variable, or secure configuration store.

Vulnerable code example

using System.Security.Cryptography;
using System.Text;

// UNSAFE: Hardcoded key literal directly used in cryptographic operation
using var aes = Aes.Create();
aes.Key = Encoding.UTF8.GetBytes("3C13a9F0b7D2e4C8f1A6b5D9e0C7f2A4"); // hardcoded secret exposed in source
aes.IV = new byte[16];
using ICryptoTransform encryptor = aes.CreateEncryptor();...

✅ Secure code example

using System;
using System.Security.Cryptography;

// SAFE: Key generated at runtime, never hardcoded in source
using var aes = Aes.Create();
aes.Key = RandomNumberGenerator.GetBytes(32); // cryptographically random key per execution
aes.IV = new byte[16];
using ICryptoTransform encryptor = aes.CreateEncryptor();...