logo

Database

Typescript Hardcoded Private Key

Description

Detects hardcoded or exposed private keys in source code files. Private keys stored directly in code represent a critical security risk as they can be used to compromise cryptographic operations, gain unauthorized system access, or decrypt sensitive data.

Weakness:

385 - Non-encrypted confidential information - Keys

Category: Information Collection

Detection Strategy

    Scans source code files for strings that match private key patterns

    Identifies content containing BEGIN PRIVATE KEY headers or similar key indicators

    Reports issues when private key material is found directly embedded in code

    Checks for both encoded (base64) and raw private key formats

    Examines string literals and variable assignments for private key content

Vulnerable code example

import * as jwt from 'jsonwebtoken';

// VULNERABLE: Hardcoded private key should never be embedded in source code
const privateKey: string = '-----BEGIN RSA PRIVATE KEY-----\nMIIBOQIBAAJBAIOLr/LyCj...\n-----END RSA PRIVATE KEY-----';

type Payload = Record<string, unknown>;

export const signToken = (payload: Payload): string => jwt.sign(payload as object, privateKey, { algorithm: 'RS256' });

✅ Secure code example

import * as jwt from 'jsonwebtoken';

// Load private key from environment variable for secure key management
const envKey = process.env.JWT_PRIVATE_KEY;
if (!envKey) throw new Error('Missing JWT_PRIVATE_KEY environment variable');
const privateKey: string = `-----BEGIN RSA PRIVATE KEY-----\n${envKey}\n-----END RSA PRIVATE KEY-----`;

type Payload = Record<string, unknown>;...