← Blog

Claude MCP skill weak cryptography in token generation and storage — SA-SKL-CRYPTO2

Cryptographic mistakes in MCP skills fall into four categories: insufficient entropy in token generation, broken hashing algorithms for password storage, deterministic encryption modes that leak plaintext patterns, and misconfigured HMAC keys that fall back to predictable defaults. Each category has well-known remediation — crypto.randomBytes, bcrypt, AES-GCM, and startup key validation — but the mistakes persist because they are easy to introduce and rarely caught by functional tests. SA-SKL-CRYPTO2 covers the four patterns most commonly found in production MCP skill repositories.

By SkillAudit  |  8 Nov 2026

Why crypto mistakes are hard to catch in MCP skill review

Weak cryptography rarely causes visible failures during development or testing. Math.random() produces numbers that look random, AES-ECB encrypts data without throwing errors, and SHA-1 produces a hash that is indistinguishable in format from a secure hash. The impact only becomes apparent when an attacker spends time analysing a database dump or brute-forcing session tokens — circumstances that do not arise in a CI test run. This makes cryptographic defects particularly resistant to detection through traditional review and test coverage. SkillAudit's SA-SKL-CRYPTO2 ruleset uses static pattern matching to flag non-CSPRNG randomness sources, deprecated hash algorithms, ECB mode cipher construction, and environment variable defaults at token or hash generation call sites.

SA-SKL-CRYPTO2 findings at a glance
CRITICALCRYPTO2-001 — Math.random() for session token generation; 32-bit Mersenne Twister state; brute-forceable in ~65 536 guesses; real-time session hijacking against active users
CRITICALCRYPTO2-002 — SHA-1 for password hashing without salt; GPU-crackable at 10 000 000 000 hashes/sec on commodity hardware; full database compromise in hours from a leaked dump
HIGHCRYPTO2-003 — AES-ECB mode for field encryption; identical plaintext produces identical ciphertext; email address column analysis reveals matching encrypted values without breaking encryption
MEDIUMCRYPTO2-004 — HMAC key stored in process.env.HMAC_SECRET defaulting to 'secret' if unset; fix: startup validation throwing if key < 32 bytes; crypto.randomBytes for local dev default only in non-production

CRYPTO2-001 — Math.random() session token has 32-bit entropy

JavaScript's Math.random() uses a seeded pseudorandom number generator — in V8, this is an implementation of xorshift128+ or similar, with roughly 128 bits of internal state but only a 32-bit effective seed in many environments. More critically, Math.random() is not designed for security-sensitive use cases: its output can be predicted by an attacker who observes a sufficient number of values (via log entries, audit trails, or other side channels that expose generated values). A session token built from Math.random() — typically something like Math.random().toString(36).slice(2) — provides at most 32–52 bits of entropy, making it brute-forceable against an active session within seconds to minutes at typical web request rates. The fix is crypto.randomBytes(32).toString('hex'), which produces 256 bits of entropy from the OS CSPRNG.

// VULNERABLE — session token from Math.random(); ~32-52 bits entropy
function generateSessionToken(): string {
  // VULNERABLE: Math.random() is seeded PRNG, not CSPRNG
  // Output is predictable with enough observed values
  // Entropy: ~32-52 bits; brute-forceable in ~65k guesses
  return Math.random().toString(36).slice(2) +
         Math.random().toString(36).slice(2);
  // result: "2j4f9xk3m1p0" — looks random, is not cryptographically secure
}

// Also vulnerable variants:
// Date.now().toString(36)  — time-based, trivially guessable
// (Math.random() * 1e17).toString(36)  — same PRNG issue
// FIXED — session token from CSPRNG; 256 bits entropy
import { randomBytes } from 'crypto';

function generateSessionToken(): string {
  // crypto.randomBytes reads from OS CSPRNG (/dev/urandom on Linux)
  // 32 bytes = 256 bits of entropy — infeasible to brute-force
  return randomBytes(32).toString('hex');
  // result: "a3f2e8b1c4d5..." — 64 hex chars, 256-bit token
}

// For URL-safe tokens (e.g., email verification links):
function generateUrlSafeToken(): string {
  return randomBytes(32).toString('base64url');
  // result: 43-char base64url string — still 256-bit entropy
}

CRYPTO2-002 — SHA-1 password hashing is GPU-crackable

SHA-1 is a general-purpose hash function optimised for speed — a modern GPU can compute roughly 10 billion SHA-1 hashes per second. Without a salt, identical passwords produce identical hashes, allowing rainbow table lookups to crack common passwords in milliseconds. Even with a salt, the speed of SHA-1 means that a 10-character password from a typical user can be cracked within hours on commodity hardware. Password hashing requires a deliberately slow function: bcrypt with a cost factor of 12 takes approximately 250ms per hash, reducing the cracking rate to roughly 4 hashes per second per GPU core. Argon2id provides even stronger protection by being both memory-hard and CPU-bound. Neither bcrypt nor argon2id is "slow" from a user-experience perspective — login takes 250ms instead of 1ms, which is imperceptible.

// VULNERABLE — SHA-1 password hashing; crackable on GPU in hours
import crypto from 'crypto';

async function hashPassword(password: string): Promise {
  // VULNERABLE: SHA-1 at 10B hashes/sec; no built-in salt; rainbow table attacks
  return crypto.createHash('sha1').update(password).digest('hex');
  // also vulnerable: md5, sha256, sha512 without key stretching
}

async function verifyPassword(password: string, stored: string): Promise {
  const hash = crypto.createHash('sha1').update(password).digest('hex');
  return hash === stored;  // also vulnerable: timing attack via === comparison
}
// FIXED — bcrypt with cost factor 12; argon2id also acceptable
import bcrypt from 'bcrypt';

const BCRYPT_ROUNDS = 12;  // ~250ms per hash on modern hardware

async function hashPassword(password: string): Promise {
  // bcrypt generates its own random 128-bit salt internally
  // cost factor 12: 2^12 = 4096 rounds; adjust up over time as hardware improves
  return bcrypt.hash(password, BCRYPT_ROUNDS);
  // stored value includes salt + rounds + hash: "$2b$12$..."
}

async function verifyPassword(password: string, stored: string): Promise {
  // bcrypt.compare uses a constant-time comparison internally
  // also handles the case where `stored` is an empty string safely
  return bcrypt.compare(password, stored);
}

// Alternative: argon2id (stronger, more modern; use if bcrypt is not already in use)
import argon2 from 'argon2';

async function hashPasswordArgon2(password: string): Promise {
  return argon2.hash(password, {
    type: argon2.argon2id,
    memoryCost: 65536,  // 64 MB memory
    timeCost: 3,        // 3 iterations
    parallelism: 1,
  });
}

CRYPTO2-003 — AES-ECB mode produces identical ciphertext for identical plaintext

AES-ECB (Electronic Codebook) mode encrypts each 16-byte block of plaintext independently using the same key. This means that two identical 16-byte plaintext blocks produce identical ciphertext blocks — a property that leaks information about the plaintext even though the encryption key is never revealed. In practice, if an MCP skill encrypts email addresses with AES-ECB, an attacker who can query the encrypted column can identify which users share the same email domain (all addresses at @gmail.com will share the same first ciphertext block), or find duplicate values without decrypting anything. AES-GCM (Galois/Counter Mode) is the correct modern replacement: it uses a random 12-byte IV per encryption, producing different ciphertext for identical plaintext, and also provides authentication that prevents ciphertext tampering.

// VULNERABLE — AES-ECB mode; identical plaintext produces identical ciphertext
import crypto from 'crypto';

const FIELD_ENC_KEY = Buffer.from(process.env.FIELD_ENC_KEY!, 'hex');

function encryptField(plaintext: string): string {
  // VULNERABLE: AES-ECB — same plaintext always produces same ciphertext
  // ECB mode has no IV; blocks encrypted independently
  // "alice@gmail.com" and "bob@gmail.com" share identical first ciphertext block
  const cipher = crypto.createCipheriv('aes-256-ecb', FIELD_ENC_KEY, null);
  return Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]).toString('hex');
}

function decryptField(ciphertext: string): string {
  const decipher = crypto.createDecipheriv('aes-256-ecb', FIELD_ENC_KEY, null);
  return Buffer.concat([
    decipher.update(Buffer.from(ciphertext, 'hex')),
    decipher.final(),
  ]).toString('utf8');
}
// FIXED — AES-256-GCM with random 12-byte IV per encryption
import crypto from 'crypto';

const FIELD_ENC_KEY = Buffer.from(process.env.FIELD_ENC_KEY!, 'hex');
// FIELD_ENC_KEY must be exactly 32 bytes (64 hex chars) for AES-256

function encryptField(plaintext: string): string {
  // 12-byte random IV — different for every encryption call
  const iv = crypto.randomBytes(12);
  const cipher = crypto.createCipheriv('aes-256-gcm', FIELD_ENC_KEY, iv);

  const encrypted = Buffer.concat([
    cipher.update(plaintext, 'utf8'),
    cipher.final(),
  ]);
  const authTag = cipher.getAuthTag();  // 16-byte GCM authentication tag

  // Store: iv (12) + authTag (16) + ciphertext; total overhead = 28 bytes
  return Buffer.concat([iv, authTag, encrypted]).toString('base64');
}

function decryptField(storedValue: string): string {
  const buf = Buffer.from(storedValue, 'base64');
  const iv      = buf.subarray(0, 12);
  const authTag = buf.subarray(12, 28);
  const encrypted = buf.subarray(28);

  const decipher = crypto.createDecipheriv('aes-256-gcm', FIELD_ENC_KEY, iv);
  decipher.setAuthTag(authTag);  // throws if ciphertext was tampered

  return Buffer.concat([
    decipher.update(encrypted),
    decipher.final(),
  ]).toString('utf8');
}

CRYPTO2-004 — HMAC key defaults to 'secret' if environment variable is unset

HMAC is used in MCP skills to sign webhooks, generate API keys, and authenticate session cookies. The security of HMAC depends entirely on the secrecy and length of the key: a key of 'secret' (6 bytes) provides 48 bits of effective entropy — far below the 128-bit minimum recommended for HMAC-SHA256. When the key is loaded with process.env.HMAC_SECRET || 'secret', any deployment that launches without the environment variable set silently uses the insecure default. Developers often test locally without the variable, leaving the default in place for weeks before anyone notices. The fix is to validate the key at application startup and throw an error immediately if it is absent or shorter than 32 bytes — making misconfiguration fail loudly rather than silently degrading to insecure operation.

// VULNERABLE — HMAC key defaults to 'secret'; silently insecure if env var missing
import crypto from 'crypto';

// VULNERABLE: 'secret' is 6 bytes = 48 bits entropy; any unset deployment is insecure
const HMAC_KEY = process.env.HMAC_SECRET || 'secret';

function signWebhookPayload(payload: string): string {
  return crypto.createHmac('sha256', HMAC_KEY).update(payload).digest('hex');
}

function verifyWebhookSignature(payload: string, signature: string): boolean {
  const expected = signWebhookPayload(payload);
  return expected === signature;  // also vulnerable: timing attack via ===
}
// FIXED — startup validation; minimum 32-byte key; timing-safe comparison
import crypto from 'crypto';

function loadHmacKey(): Buffer {
  const keyHex = process.env.HMAC_SECRET;

  if (!keyHex) {
    // Throw at startup — fail loudly rather than silently using a weak default
    // NODE_ENV check: generate a random key for local dev only, never in production
    if (process.env.NODE_ENV === 'production') {
      throw new Error('HMAC_SECRET env var is required in production');
    }
    // Local dev only: generate a random key (not persisted — session tokens will
    // invalidate on restart, which is acceptable in development)
    console.warn('HMAC_SECRET not set — generating ephemeral key for local dev');
    return crypto.randomBytes(32);
  }

  const keyBuf = Buffer.from(keyHex, 'hex');
  if (keyBuf.length < 32) {
    throw new Error(`HMAC_SECRET must be at least 32 bytes; got ${keyBuf.length}`);
  }

  return keyBuf;
}

// Validated once at module load — any error surfaces immediately on startup
const HMAC_KEY: Buffer = loadHmacKey();

function signWebhookPayload(payload: string): string {
  return crypto.createHmac('sha256', HMAC_KEY).update(payload, 'utf8').digest('hex');
}

function verifyWebhookSignature(payload: string, signature: string): boolean {
  const expected = signWebhookPayload(payload);
  // timingSafeEqual prevents timing attacks; both buffers must be same length
  if (expected.length !== signature.length) return false;
  return crypto.timingSafeEqual(
    Buffer.from(expected),
    Buffer.from(signature),
  );
}

Detection with SkillAudit

SkillAudit's SA-SKL-CRYPTO2 rule set detects weak cryptography through static analysis of Node.js crypto API usage. The CSPRNG check flags any occurrence of Math.random(), Date.now(), or performance.now() used as a source of randomness for security-sensitive values: tokens, nonces, keys, or salts. The hash algorithm check flags createHash('md5'), createHash('sha1'), and createHash('sha256') at password storage call sites (identified by proximity to password column writes). The cipher mode check flags createCipheriv calls with 'aes-256-ecb', 'aes-128-ecb', or 'des-ecb' in any context. The key validation check flags HMAC and symmetric encryption key reads that use the || 'default' pattern without startup length validation. See also SA-SKL-AUTH4 for JWT signing key issues.

Run SA-SKL-CRYPTO2 on your skill: Paste your MCP skill's GitHub URL at skillaudit.dev to get a full scan. The free tier covers public repositories and returns a shareable security badge.

FindingSeverityVulnerable patternFix
CRYPTO2-001CriticalMath.random() for session token; 32–52 bit entropy; brute-forceable in ~65k guessescrypto.randomBytes(32).toString('hex') — 256-bit CSPRNG token
CRYPTO2-002CriticalSHA-1 password hashing; 10B hashes/sec on GPU; full DB cracked in hours from leaked dumpbcrypt.hash(password, 12) or argon2.hash(password, { type: argon2id })
CRYPTO2-003HighAES-ECB mode; identical plaintext → identical ciphertext; pattern leaks without key exposureAES-256-GCM with random 12-byte IV per call; store IV + authTag + ciphertext
CRYPTO2-004MediumHMAC key defaults to 'secret' (48-bit entropy) when env var is absent; silent insecure fallbackStartup validation: throw if key absent or <32 bytes in production; ephemeral random key for local dev only