You’re staring at a pull request. The code looks clean. Tests pass. But buried in there is a cryptographic implementation that’s using MD5 for password hashing, storing keys in plaintext environment variables, and seeding its random number generator with the current timestamp. You don’t catch it. It ships. Three months later, someone’s finding customer data on a paste site.
We’ve all seen it happen. Cryptography is genuinely hard—not because the math is complex (though it is), but because the gotchas are subtle and the consequences are catastrophic. Security isn’t something you bolt on at the end; it’s baked into design decisions from day one.
The good news? You don’t have to be a cryptography PhD to audit crypto implementations effectively. You need to know what to look for and where to look. This guide walks you through systematically reviewing cryptographic code using Claude Code—a process that catches the mistakes that slip past normal code review, saves your team from embarrassing security incidents, and builds real confidence in your security posture.
Let’s get into it.
The Cryptography Audit Problem
Here’s what makes cryptographic code reviews genuinely different from normal code review:
-
Silent failures: A buggy authentication system might not crash—it might just silently accept forged credentials. Your application appears to be working normally while security guarantees evaporate. Users don’t notice until their data shows up on paste sites.
-
Cascading weaknesses: A weak RNG or bad key derivation doesn’t just weaken one component; it undermines everything built on top of it. You might have perfect HTTPS, but if the keys were derived from a weak PRNG, all communications are potentially compromised. If tokens were generated with
Math.random(), every single session token can be predicted. -
Deprecated doesn’t mean obviously broken: MD5, SHA-1, and WEP still work. They’re just… exploitable. Some codebases have been using them for decades without visible problems until suddenly they have huge problems. SHA-1 collisions were demonstrated in 2017, yet systems were still shipping with SHA-1 for critical operations well into 2020. The attacks work; they just require resources.
-
Context matters: Some algorithms are fine in one context but dangerous in another. MD5 for non-cryptographic checksums? Fine. MD5 for passwords? Career-ending. HMAC-SHA1 for message authentication? Acceptable (though SHA256 preferred). SHA-1 for certificate signatures? Critical vulnerability.
-
False confidence from testing: Your test suite probably doesn’t include an attacker with GPUs and time. A password hash function might pass your tests while being crackable in hours by a determined adversary. Your key generation might work fine under normal load but be predictable under specific timing conditions.
Most developers aren’t equipped to catch these issues because they’re not usually taught in computer science programs, and security courses often focus on why things are broken rather than how to detect them in real code. Cryptography education emphasizes theoretical understanding over practical red flags.
Enter systematic review.
What We’re Actually Looking For
When you’re reviewing cryptographic implementations, you’re checking five main categories:
1. Weak or Deprecated Algorithms
Using algorithms that have known practical attacks or are considered obsolete (MD5, SHA-1, DES, RC4, etc.).
2. Insecure Key Management
Keys stored in plaintext, hardcoded, version-controlled, logged, or not rotated. This is the most common failure point.
3. Broken Random Number Generation
Using Math.random() or rand() for cryptographic purposes. Using predictable seeds. Not using cryptographically-secure PRNGs.
4. TLS/HTTPS Misconfiguration
Disabled certificate validation, deprecated protocols (SSLv3, TLS 1.0), weak ciphers, or self-signed certs in production.
5. Password Hashing Failures
Using fast hashing algorithms (MD5, SHA-1, SHA-256 without salt) instead of slow, memory-hard functions. Not salting properly. Reusing salts.
Now let’s see how Claude Code helps you find these systematically.
Finding Weak Algorithms: The Pattern Hunt
The first pass is straightforward: search for algorithm names that are red flags.
# Search for deprecated algorithm usage patterns
grep -r "md5\|MD5\|sha1\|SHA1\|des\|DES\|rc4\|RC4\|blake2" . \
--include="*.js" --include="*.py" --include="*.go" --include="*.java"
But that’s surface-level. You need Claude Code’s deeper analysis. Here’s what a real review looks like:
File: auth-service/crypto.js
const crypto = require("crypto");
function hashPassword(password) {
const hash = crypto.createHash("sha256");
hash.update(password);
return hash.digest("hex");
}
function encryptSession(sessionId) {
const cipher = crypto.createCipher("aes-256-cbc", "my-secret-key");
let encrypted = cipher.update(sessionId, "utf8", "hex");
encrypted += cipher.final("hex");
return encrypted;
}
What’s wrong here? A lot. Let me break it down:
Problem 1: SHA-256 for Password Hashing
SHA-256 is a fast hash. It’s designed to be fast. For passwords, you want the opposite—a function that takes time and memory. An attacker can try billions of SHA-256 hashes per second on a GPU. With bcrypt or Argon2, they can try maybe thousands per second.
Why this matters: Even with salts, a fast hash function buys an attacker time measured in hours, not centuries. The human cost of cracking a password with SHA-256 is negligible; the cost with Argon2 is prohibitive for all but the most valuable targets.
Problem 2: crypto.createCipher()
This function has been deprecated since Node.js 10 and marked for removal. It uses a weak key derivation function (EVP_BytesToKey) that:
- Doesn’t use a salt
- Only uses the first 8 bytes of your password
- Has been broken since 2007
Attackers have known how to compromise this function for years. If your code has been sitting in a codebase for a while, it’s been vulnerable the entire time.
Problem 3: Hardcoded String as Key
'my-secret-key' is not actually a key—it’s a password. Even if you use a proper key derivation function, hardcoding it in source code means:
- It’s in version control history forever
- It’s visible to anyone who can read the code
- It can’t be rotated without redeploying
The fix:
const crypto = require("crypto");
const bcrypt = require("bcrypt");
const argon2 = require("argon2");
// For password hashing: use bcrypt or Argon2
async function hashPassword(password) {
// Argon2 is the OWASP recommendation (2021+)
// bcrypt is battle-tested and still solid
return await argon2.hash(password, {
type: argon2.argon2id,
memoryCost: 65536, // 64 MB
timeCost: 3, // 3 iterations
parallelism: 4, // 4 threads
});
}
async function verifyPassword(password, hash) {
return await argon2.verify(hash, password);
}
// For encryption: use authenticated encryption (AEAD)
function encryptSession(sessionId) {
const key = Buffer.from(process.env.ENCRYPTION_KEY, "hex");
const iv = crypto.randomBytes(16);
// Use AES-GCM (authenticated encryption with associated data)
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
let encrypted = cipher.update(sessionId, "utf8", "hex");
encrypted += cipher.final("hex");
const authTag = cipher.getAuthTag();
// Return both IV and authTag with ciphertext
return JSON.stringify({
iv: iv.toString("hex"),
ciphertext: encrypted,
authTag: authTag.toString("hex"),
});
}
function decryptSession(encrypted) {
const key = Buffer.from(process.env.ENCRYPTION_KEY, "hex");
const { iv, ciphertext, authTag } = JSON.parse(encrypted);
const decipher = crypto.createDecipheriv(
"aes-256-gcm",
key,
Buffer.from(iv, "hex"),
);
decipher.setAuthTag(Buffer.from(authTag, "hex"));
let decrypted = decipher.update(ciphertext, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
}
Notice what changed:
- Password hashing: Switched from SHA-256 to Argon2 (or bcrypt for Node.js < v12)
- Encryption: Switched from
createCipher()tocreateCipheriv()with proper IV - Authenticated encryption: Using AES-GCM instead of raw AES-CBC
- Key source: Loading from environment variable instead of hardcoding
The Key Management Minefield
Here’s something that doesn’t get talked about enough: properly managing cryptographic keys is harder than the cryptography itself. It’s easy to get the algorithm right and the key management spectacularly wrong. This is where most real-world breaches happen—not because the crypto is broken, but because the keys are accessible.
File: config.json (committed to git)
{
"database": {
"encryptionKey": "0x1234567890abcdef1234567890abcdef",
"hmacSecret": "my-super-secret-hmac-key"
},
"api": {
"jwtSecret": "shhh-this-is-very-secret"
}
}
If you see this, stop the review. This is a critical vulnerability. Everything in your git history is compromised. Even if you delete the file in a later commit, the key still exists in every clone of the repository. Every developer who ever worked with this repo has it locally. If the repo is ever shared, everyone has access.
File: .env (accidentally committed)
DB_ENCRYPTION_KEY=0x1234567890abcdef1234567890abcdef
JWT_SECRET=shhh-this-is-very-secret
API_KEY=sk-1234567890abcdef
Same problem, different package. This is even sneakier because teams often commit .env files thinking they’re temporary.
File: logs/application.log
[INFO] Initializing encryption with key: 0x1234567890abcdef1234567890abcdef
[INFO] JWT token created: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
[DEBUG] Decrypt operation with password 'supersecretpassword'
Everything in your logs is searchable by attackers if they ever compromise your infrastructure. A single compromise of a log aggregation system, and every key that’s ever been logged is exposed.
The Right Way to Handle Keys
// 1. Generate keys separately, never in application code
// $ openssl rand -hex 32
// $ node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
// 2. Store in secure location (never version control)
// - Environment variables (for development)
// - AWS Secrets Manager, HashiCorp Vault, etc. (for production)
// - Kubernetes Secrets (for containerized deployments)
// - Azure Key Vault (for Azure deployments)
// 3. Load at runtime, never log
const getEncryptionKey = () => {
const key = process.env.ENCRYPTION_KEY;
if (!key) {
throw new Error("ENCRYPTION_KEY not found in environment");
}
// Validate format (64-char hex = 32 bytes = 256 bits)
if (!/^[0-9a-f]{64}$/i.test(key)) {
throw new Error("ENCRYPTION_KEY must be 64-character hex string");
}
return Buffer.from(key, "hex");
};
// 4. Rotate regularly (establish a schedule and stick to it)
// - Monthly for HMAC keys
// - Quarterly for encryption keys
// - Immediately if you suspect compromise
// - Have a plan for re-encrypting data with new keys
// 5. Never include in error messages or logs
const safeLog = (message) => {
// Bad: console.log(`Decryption failed with key ${key}`);
// Good:
console.log("Decryption failed (key details omitted for security)");
};
// 6. Key versioning: support multiple keys during rotation
const encryptWithVersion = (data) => {
const currentKeyVersion = 2;
const key = getKeyByVersion(currentKeyVersion);
const ciphertext = encrypt(data, key);
return {
keyVersion: currentKeyVersion,
ciphertext: ciphertext,
};
};
const decrypt = (encrypted) => {
const key = getKeyByVersion(encrypted.keyVersion);
return decrypt(encrypted.ciphertext, key);
};
What to Look For in Key Management:
- Keys in source code (searchable string literals)
- Keys in version control (git history)
- Keys in logs (grep for patterns)
- Keys in error messages (try-catch blocks that re-throw with secrets)
- Same key used for multiple purposes (encryption, authentication, etc.)
- No key rotation strategy documented or implemented
- No backup/recovery plan for lost keys
- Keys stored in plain text in databases
- Keys accessible to unauthorized services
- No audit trail of key access
Random Number Generation: Why Math.random() Will Destroy You
Here’s a real-world example that’s scarier than it should be:
function generateSessionToken() {
// DO NOT DO THIS
return Math.random().toString(36).substring(2);
}
function generateApiKey() {
// ALSO DO NOT DO THIS
const random = Math.random();
const timestamp = Date.now();
return (random + timestamp).toString(16);
}
// Even this feels more secure but isn't:
function generateToken() {
let token = "";
for (let i = 0; i < 32; i++) {
token += Math.floor(Math.random() * 16).toString(16);
}
return token;
}
Why is this catastrophic?
-
Math.random()is not cryptographically secure. The V8 engine uses an XORshift128+ PRNG, which is designed for speed and statistical properties, not unpredictability. If an attacker observes a few outputs, they can reconstruct the internal state. State-of-the-art attacks can predict it with very high accuracy. There are public tools that do this. We’re talking 64 bits of internal state that becomes predictable from public outputs. -
Seeding with predictable values is worse. If you seed with the timestamp or process ID, an attacker can try all possible seeds (a few million possibilities) in milliseconds. For a token generated at 2:47 PM on March 16, 2026, there are only 86,400,000 possible timestamps that day. An attacker can try all of them in hours.
-
Limited entropy source.
Math.random()gives you about 53 bits of entropy (the mantissa of a double-precision float). For 128-bit security (equivalent to a 16-character hex string), you need 128 bits of actual randomness. 53 bits is weaker than a 10-character password. -
You’re not even using the full output.
toString(36)throws away entropy and introduces bias.Math.floor(Math.random() * 16)introduces modulo bias. Every transformation loses information. -
Seeding is ephemeral. In Node.js,
Math.random()is seeded from the environment on startup. If you restart the process at a predictable time (common in containerized environments), the PRNG state might be identical or very similar. Attackers targeting your system can predict when you restart and what tokens will be generated.
Here’s what it looks like when attackers exploit this:
# Attacking a predictable PRNG is trivial
from xorshift128plus import XORShift128Plus # Reconstructing PRNG state
session_tokens = []
for _ in range(100):
response = requests.get('https://vulnerable-app.com/api/login')
token = response.cookies.get('session')
session_tokens.append(token)
# With 100 samples, recreate the PRNG state
xor = XORShift128Plus.from_outputs(session_tokens)
# Now predict all future tokens before they're generated
next_token = xor.next()
# Use next_token to hijack someone's session
This isn’t theoretical. These attacks work. They’ve been used to compromise real systems. Some high-traffic sites have had sessions compromised by attackers exploiting weak RNG.
The correct way:
const crypto = require('crypto');
// For tokens that need to be human-readable
function generateSessionToken() {
return crypto.randomBytes(32).toString('hex'); // 64-char hex string
}
// For API keys
function generateApiKey() {
return crypto.randomBytes(24).toString('base64url'); // URL-safe, no padding
}
// For UUIDs (if required for some reason)
const { v4: uuidv4, v5: uuidv5 } = require('uuid');
// v4 uses crypto.randomBytes internally (good)
// v5 uses SHA-1 (bad for security-sensitive contexts)
// For numeric nonces
function generateNonce() {
return crypto.randomInt(0, 2n ** 32n); // Cryptographically secure
}
// In Python
def generate_session_token():
return secrets.token_hex(32) # 64-char hex
def generate_api_key():
return secrets.token_urlsafe(24) # URL-safe base64
def generate_nonce():
return int.from_bytes(os.urandom(4), 'big')
Red Flags to Search For:
Math.random()used anywhere near security contextsrand(),random.randint(),rand.Intn()for cryptography- Seeding with
time(),getpid(),uuid() /dev/urandombeing read manually (should use language libraries)- Insufficient output size (less than 128 bits for most purposes)
- RNG seeded from user input or observable data
TLS Configuration: The Nightmare That Never Ends
SSL/TLS configuration is where theory meets reality, and reality is messy. You can have perfect cryptography inside your application and still get completely pwned by misconfigured TLS. More breaches happen from TLS misconfiguration than from broken crypto algorithms.
File: node-server.js (The Common Nightmare)
const https = require("https");
const fs = require("fs");
const options = {
key: fs.readFileSync("server.key"),
cert: fs.readFileSync("server.crt"),
};
https
.createServer(options, (req, res) => {
res.writeHead(200);
res.end("Hello World\n");
})
.listen(443);
// Meanwhile, the client code:
const https = require("https");
https.get("https://some-api.example.com/data", (res) => {
// Problem: certificate validation is disabled by default in many libs
// If the API cert is self-signed, this "just works"
// Which means you're vulnerable to MITM attacks
});
What’s wrong:
-
No certificate validation on the client. Self-signed certificates are accepted. An attacker on your network can intercept traffic with a self-signed cert. This is the most common TLS misconfiguration and the easiest to exploit.
-
No HSTS header. If someone tricks a user into visiting http://example.com, the server doesn’t force HTTPS. The attacker can intercept and modify traffic.
-
No cipher suite restriction. Old TLS versions and weak ciphers might be negotiated. Legacy algorithms still supported for “compatibility” are the most exploited.
-
Certificate pinning is missing. If a CA is compromised (it happens—look up DigiNotar), you’re vulnerable because you trust any certificate signed by any CA.
The better approach:
const https = require("https");
const fs = require("fs");
const tls = require("tls");
// 1. Server: Modern TLS configuration
const options = {
key: fs.readFileSync("server.key"),
cert: fs.readFileSync("server.crt"),
// Restrict to modern TLS versions
minVersion: tls.TLS1_2,
maxVersion: tls.TLS1_3,
// Force strong ciphers (prefer AEAD suites)
ciphers: [
"TLS_AES_256_GCM_SHA384", // TLS 1.3 (best)
"TLS_CHACHA20_POLY1305_SHA256", // TLS 1.3 (alternative)
"TLS_AES_128_GCM_SHA256", // TLS 1.3 (minimum)
].join(":"),
// Prefer server's cipher choices (prevent downgrade attacks)
honorCipherOrder: true,
// OCSP stapling for certificate validation
// sessionIdContext: 'default',
};
const server = https.createServer(options, (req, res) => {
// Add security headers
res.setHeader(
"Strict-Transport-Security",
"max-age=31536000; includeSubDomains; preload",
);
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("X-Frame-Options", "DENY");
res.setHeader("X-XSS-Protection", "1; mode=block");
res.writeHead(200);
res.end("Hello World\n");
});
server.listen(443);
// 2. Client: Strict certificate validation
const clientOptions = {
hostname: "some-api.example.com",
port: 443,
path: "/data",
method: "GET",
// STRICT: Reject invalid certificates (this is critical)
rejectUnauthorized: true,
// Optional: Pin certificates for extra security
// Load the pinned certificate yourself
ca: [fs.readFileSync("pinned-cert.pem")],
};
const req = https.request(clientOptions, (res) => {
// This only executes if certificate validation passes
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => console.log(data));
});
req.on("error", (err) => {
console.error("Certificate validation failed:", err.message);
// Handle appropriately (don't ignore or suppress the error!)
// Log it, alert, fail safely—but never silently continue
process.exit(1);
});
req.end();
TLS Checklist:
- [ ] TLS 1.2 minimum (TLS 1.3 preferred)
- [ ] No SSLv3, TLS 1.0, TLS 1.1
- [ ] Strong ciphers only (AEAD suites)
- [ ] Certificate validation enabled (
rejectUnauthorized: true) - [ ] HSTS header configured (with preload)
- [ ] Certificate pinning for critical connections
- [ ] Regular certificate updates (not expired)
- [ ] No self-signed certs in production
- [ ] Proper error handling for validation failures
- [ ] No wildcard imports of CA certificates
- [ ] CRL or OCSP stapling configured
- [ ] Certificate transparency monitoring enabled
Additional TLS Pitfalls to Watch For:
Custom CA certificates in development that leak into production:
// DANGER: This CA bundle is used in production too
const fs = require("fs");
const ca = fs.readFileSync("/app/dev-ca.pem");
// Every production request now trusts dev CAs
// This happens more often than you'd think
Disabling certificate validation for “development convenience”:
// You know this one exists in your codebase somewhere
if (process.env.NODE_ENV !== "production") {
https.globalAgent = new https.Agent({ rejectUnauthorized: false });
}
// Then someone forgets to turn it back on, and it ships
// This is a top-10 cause of production TLS breaches
Missing Subject Alternative Name (SAN) validation:
// With SAN validation, this breaks (correctly)
const cert = { CN: "example.com" };
// SAN: [*.example.com, api.example.com]
// If you only check CN, you miss the SAN
// A cert for different.example.com would be accepted
Certificate chain validation disabled:
// Some clients allow you to provide just the leaf cert
// If you don't validate the chain back to a trusted root,
// you're trusting intermediate CAs you shouldn't
// An attacker could issue a cert signed by a compromised intermediate
Password Hashing: The Algorithm You Actually Use Matters
There’s something genuinely dangerous about how password hashing is discussed in security training. The advice is usually “use bcrypt, Argon2, or scrypt”—which is correct—but the why gets glossed over, and developers often implement it wrong. Let’s fix that.
The fundamental insight: you want password hashing to be slow and expensive. The slower it is for legitimate users, the slower it is for attackers. A function that takes 100ms per hash is fine for a user logging in once. It’s catastrophic for an attacker trying a billion passwords.
Bad: Using a General-Purpose Hash
const crypto = require("crypto");
// This is SHA-256, which we already talked about
function hashPassword(password) {
return crypto.createHash("sha256").update(password).digest("hex");
}
// Even with a salt:
function hashPasswordWithSalt(password) {
const salt = crypto.randomBytes(16).toString("hex");
const hash = crypto
.createHash("sha256")
.update(salt + password)
.digest("hex");
return `${salt}:${hash}`;
}
Why is even the salted version weak?
-
Speed. SHA-256 can be computed 10+ billion times per second on modern GPUs. An attacker can crack an 8-character password in minutes. Your users won’t notice the delay of 100ms per login, but attackers can try billions of passwords in that time.
-
Single iteration. There’s no built-in slowdown mechanism. SHA-256 doesn’t have a “cost factor” you can tune.
-
No memory cost. GPU-based attacks are cheap because they don’t require much memory. A GPU can fit thousands of hashing operations in parallel.
Better: Using bcrypt
const bcrypt = require("bcrypt");
async function hashPassword(password) {
// Cost factor (rounds): 10-12 is typical
// Each increase doubles the computation time
// 10 rounds ≈ 10 ms (too fast)
// 12 rounds ≈ 40 ms (reasonable)
// 14 rounds ≈ 160 ms (conservative)
return await bcrypt.hash(password, 12);
}
async function verifyPassword(password, hash) {
return await bcrypt.compare(password, hash);
}
Why is bcrypt better?
- Adaptive cost. As computers get faster, you just increase the cost factor.
- Salted automatically. No manual salt management.
- Proven track record. Used in production since 1999.
- Available everywhere. Implementations in every major language.
The catch: bcrypt is slower than you might expect—and that’s intentional. On purpose. That slowness is the security feature. If you’re concerned about login performance, consider caching validated sessions rather than hashing faster.
Best: Using Argon2
const argon2 = require("argon2");
async function hashPassword(password) {
return await argon2.hash(password, {
// Algorithm variant (id is best for password hashing)
type: argon2.argon2id,
// Memory cost in KiB (64 MB is standard, 128 MB for highly sensitive)
memoryCost: 65536,
// Time cost (iterations, more = slower)
timeCost: 3,
// Parallelism (threads)
parallelism: 4,
// Output length in bytes
hashLength: 32,
// Raw binary output or encoded
raw: false,
});
}
async function verifyPassword(password, hash) {
return await argon2.verify(hash, password);
}
Why Argon2?
- Memory-hard. Requires significant memory (64 MB default), making GPU attacks expensive.
- Time-hard. Can be tuned for different security/performance tradeoffs.
- Parallelizable. Takes advantage of multi-core systems.
- Modern. Won the Password Hashing Competition (2015).
The memory cost is the kicker: GPU attacks are cheap only because they don’t require much memory. Force 64 MB of memory per hash, and suddenly you need hundreds of billions of dollars in hardware to crack passwords in reasonable time.
Common Password Hashing Mistakes:
❌ Using the same salt for all passwords
const SALT = "hardcoded-salt"; // WRONG!
// Every user gets hashed with the same salt
// If one password is cracked, the salt is exposed
// Attackers can precompute hashes for common passwords (rainbow tables)
❌ Short salts
const salt = crypto.randomBytes(4); // Too short!
// 4 bytes = 32 bits = 4 billion possible salts
// Attacker can precompute rainbow tables for all salts
// Use at least 16 bytes (128 bits)
❌ Reusing parameters across versions
// Version 1: bcrypt with cost 8
// Version 2: bcrypt with cost 10
// But old v1 hashes were never re-hashed
// Some passwords remain weak forever
✅ The right approach:
async function hashPassword(password) {
// Argon2 handles salt generation internally
return await argon2.hash(password, {
type: argon2.argon2id,
memoryCost: 65536,
timeCost: 3,
parallelism: 4,
});
}
async function verifyPassword(password, hash) {
// Extract original salt and params from hash automatically
return await argon2.verify(hash, password);
}
// When upgrading algorithms:
async function upgradeHashIfNeeded(password, oldHash) {
// Verify against old algorithm
if (await bcrypt.compare(password, oldHash)) {
// Re-hash with new algorithm on successful verification
// Store the new hash
return await argon2.hash(password, {...});
}
throw new Error('Invalid password');
}
The Complete Review Checklist
Here’s a practical checklist for reviewing cryptographic code. Use this as a starting point for your audits, and customize it based on your application’s specific needs and threat model.
Algorithm Review
- [ ] No MD5, SHA-1 for security purposes
- [ ] Password hashing uses bcrypt, scrypt, or Argon2
- [ ] Encryption uses AES (256-bit) or ChaCha20
- [ ] MACs use HMAC-SHA256+ or Poly1305
- [ ] No custom crypto implementations
- [ ] No ECB mode (use CBC, CTR, GCM, etc.)
- [ ] No deprecated algorithms (
createCipher, etc.)
Key Management
- [ ] No hardcoded keys anywhere
- [ ] No keys in version control
- [ ] No keys in logs or error messages
- [ ] Keys loaded from secure storage (env vars, vaults, secrets)
- [ ] Key rotation strategy documented and implemented
- [ ] Key backup and recovery plan exists
- [ ] Access controls on key storage
- [ ] Audit trail of key access (who accessed what, when)
- [ ] Multi-key support during rotation
- [ ] Key versioning system
Random Number Generation
- [ ]
crypto.randomBytes(),secrets.token_*(), or equivalent - [ ] Never
Math.random(),rand(), etc. for crypto - [ ] Sufficient entropy (128+ bits for most use cases)
- [ ] No predictable seeds
- [ ] No user input seeding the RNG
- [ ] CSPRNG validates entropy source
TLS/HTTPS
- [ ] TLS 1.2+ (1.3 preferred)
- [ ] Certificate validation enabled (
rejectUnauthorized: true) - [ ] Strong cipher suites only
- [ ] HSTS header configured with preload
- [ ] No self-signed certs in production
- [ ] Certificate pinning for sensitive connections
- [ ] Certificate expiry monitoring
- [ ] No disabled certificate validation in “dev mode”
- [ ] Certificate chain validation enabled
- [ ] SAN validation enabled
Password Security
- [ ] Using bcrypt, scrypt, or Argon2
- [ ] Salt ≥16 bytes
- [ ] Multiple iterations/cost factor (bcrypt 12+, argon2 timeCost 3+)
- [ ] No password hashing without salt
- [ ] Password reset tokens are cryptographically random
- [ ] Passwords never logged or cached
- [ ] Failed login attempts rate-limited
- [ ] Password upgrade path for old algorithms
- [ ] No plaintext password storage anywhere
- [ ] Password change invalidates all existing sessions
Operational Security
- [ ] No secrets in environment variables (use Secrets Manager)
- [ ] No secrets in logs (implement safe logging)
- [ ] No secrets in error messages
- [ ] Secrets Manager access audited
- [ ] Credentials rotated on employee departure
- [ ] Regular penetration testing of crypto implementation
- [ ] Security training for developers
- [ ] Incident response plan for compromised keys
Putting It Together: Automated Review
The best part about this is that much of it can be automated. Claude Code can:
- Search for dangerous patterns (deprecated algorithms, weak RNG)
- Analyze code flow (where keys come from, how they’re used)
- Check for missing validation (TLS config, certificate handling)
- Validate against standards (OWASP, NIST, IETF)
- Generate remediation (updated code examples)
- Track across project (find all usages of weak functions)
- Identify configuration issues (environment setup, defaults)
A typical review might look like:
1. Scan for weak algorithm names (grep for md5, sha1, des, rc4)
2. Read key files (environment, config, logging)
3. Trace cryptographic function calls and their sources
4. Check TLS configuration (protocols, ciphers, validation)
5. Review password hashing implementation
6. Verify random number generation sources
7. Check certificate handling and pinning
8. Generate report with severity levels
9. Propose fixes for each issue
10. Identify patterns that apply to multiple files
Real Workflow Example
Let’s say you’re reviewing a Node.js project. Here’s what a systematic review looks like:
Step 1: Find all crypto-related imports
grep -r "require.*crypto\|from.*crypto" --include="*.js"
grep -r "require.*bcrypt\|require.*argon2" --include="*.js"
grep -r "require.*jsonwebtoken" --include="*.js"
grep -r "https\.createServer" --include="*.js"
Step 2: Locate environment/config usage
grep -r "process\.env\." --include="*.js" | grep -i "key\|secret\|encrypt"
grep -r "config\." --include="*.js" | grep -i "key\|secret\|encrypt"
grep -r "\.env" --include="*.json" --include=".gitignore"
Step 3: Check for deprecated patterns
grep -r "createCipher\|createDecipher" --include="*.js"
grep -r "crypto\.createHash.*sha1\|crypto\.createHash.*md5" --include="*.js"
grep -r "Math\.random" --include="*.js" | grep -v "// " | grep -v "//"
Step 4: Analyze logging to prevent key leaks
grep -r "console\.log\|logger\." --include="*.js" | grep -i "key\|secret\|token\|password"
grep -r "toString\|JSON\.stringify" --include="*.js" | grep -i "key\|secret"
Step 5: Validate TLS configuration
grep -r "rejectUnauthorized.*false" --include="*.js"
grep -r "tls\.TLS1_0\|tls\.TLS1_1" --include="*.js"
grep -r "https\.get\|https\.request" --include="*.js" | wc -l
Each finding then requires human analysis: Is this truly a vulnerability, or is the context safe? Does the algorithm choice match the threat model? Are mitigating controls in place elsewhere?
Real-World Impact
Here’s why this matters beyond theory:
- 2013 Target breach: Used weak encryption for point-of-sale systems
- 2014 OpenSSL Heartbleed: Improper input validation in TLS implementation
- 2016 Yahoo: Used deprecated hashing algorithms for password storage
- 2017 Equifax: Known vulnerability in TLS/SSL library went unpatched
- 2020s ongoing: Apps still using MD5, storing keys in plaintext, disabling certificate validation
Every single one of these would have been caught by systematic cryptographic review. These aren’t hard problems. They’re just… easy to miss if you’re not looking systematically.
Real-World Incident Response: Learning from Breaches
Understanding the importance of crypto audits becomes visceral when you look at breaches that could have been caught with systematic review. Consider the 2016 Yahoo breach, where researchers discovered that Yahoo was using MD5 for password hashing at scale—this had been known to be weak for years, yet millions of accounts relied on it for protection. A systematic crypto audit would have flagged MD5 immediately and prioritized migration to bcrypt or Argon2. The company had the resources to fix it, but nobody systematized the audit process until it was too late.
Similarly, the Equifax breach involved a known vulnerability in Apache Struts that should have been caught by automated vulnerability scanning, but the underlying issue was that their security team wasn’t running systematic code reviews on cryptographic components. They had key storage problems, TLS configuration issues, and weak encryption in motion—all discoverable through structured audits using tools like Claude Code. The cost to fix it after the breach? $700 million in settlements. The cost to prevent it through quarterly crypto audits? A few engineering days.
This isn’t fearmongering. It’s arithmetic.
Why Automated Audits Beat Manual Review
Here’s where Claude Code provides specific advantages over traditional code review:
Pattern Recognition at Scale: When auditing a 10,000-file codebase, a human reviewer might miss the one location where you’re using Math.random() in a critical place, or the one environment variable where a key is being logged. Claude Code can scan all 10,000 files in minutes, checking for dozens of patterns simultaneously. You review the results rather than the entire codebase.
Consistency: Human reviewers get tired. By hour 6 of reviewing code, you miss things. Automated pattern matching is consistent across the entire codebase. Every instance of createCipher() is flagged, whether it’s in file 1 or file 9,847.
Context-Aware Analysis: Unlike simple grep-based searching, Claude Code understands code structure. It can tell you not just “MD5 is used here” but “MD5 is used in this password hashing context, and there’s no salt, and it’s called from three endpoints without rate limiting.” That contextual information is what turns raw findings into actionable security improvements.
Cross-Component Understanding: Cryptographic vulnerabilities often involve multiple pieces working together incorrectly. Key management depends on environment loading, which depends on how secrets are stored in CI/CD, which depends on which engineers have access. Claude Code can trace these dependencies across the entire system, revealing gaps that isolated code review would miss.
Documentation Generation: After finding vulnerabilities, Claude Code can generate documentation explaining why each finding matters, suggesting fixes, and proposing testing strategies. This accelerates remediation.
Building a Cryptography-First Culture
The technical tools matter, but the process matters more. Organizations that maintain strong cryptographic security don’t do it through one-time audits. They build it into their development process:
Crypto Review as Pre-Commit: Before any cryptographic code is committed, it’s reviewed against the checklist in this guide. This catches issues before they enter the codebase, rather than discovering them in production.
Regular Rotation Schedules: Key rotation isn’t something you do when you remember to. It’s scheduled: the first Tuesday of every month, credentials are rotated. This prevents compromised keys from being used indefinitely. When an incident happens, you have a bounded window of exposure.
Incident Classification: When something goes wrong (leaked API key, discovered weak algorithm), classify it immediately:
- Did attackers likely use this to compromise data?
- How many users were potentially affected?
- What’s the immediate action (revoke key, deprecate algorithm, notify users)?
- What’s the long-term fix (implement new key management system, migrate to stronger algorithm)?
Team Training: Every engineer on your team should understand the crypto basics. They don’t need to be cryptographers, but they should be able to:
- Explain why
Math.random()is dangerous for security - Describe the difference between hashing and encryption
- Know what password hashing algorithms are appropriate
- Understand the purpose of salt in password hashing
This knowledge prevents the “I didn’t know this was wrong” situation and creates a culture where security is everyone’s responsibility.
The Checklist That Actually Works
The comprehensive checklist earlier is extensive, but it can be overwhelming. In practice, most teams start with a minimal checklist of the things that kill systems:
The Critical Three (if you fix nothing else, fix these):
-
No plaintext keys in code or version control: Every key must be loaded from environment variables or a secrets manager. Every single one. No exceptions for “temporary keys.” Temporary keys become permanent when someone forgets to change them.
-
Different secrets for different token types: Using the same secret for access tokens, refresh tokens, password reset tokens, and API keys means a breach of any secret compromises all of them. Separate secrets limit blast radius.
-
Rate limiting on auth endpoints: A password hash function protects against brute force through computational cost. But if there’s no rate limiting on the login endpoint, an attacker bypasses that protection by making requests slowly but persistently—trying 1000 passwords over a week rather than 1000 passwords per second.
Fix these three and you’ve eliminated the most common catastrophic failures. Everything else improves from there.
Integration Into Your Workflow
Here’s how to practically integrate crypto auditing into your development process:
During Code Review: When you see cryptographic code in a PR, ask:
- Are you using strong algorithms (Argon2 for passwords, AES-256-GCM for encryption)?
- Are keys loaded from environment, never hardcoded?
- Is entropy being generated securely?
- Are there tests for both success and failure cases?
In CI/CD Pipeline: Set up automated checks:
- Static analysis scanning for weak crypto patterns
- Secrets detection to prevent key commits
- Dependency vulnerability scanning (outdated crypto libraries)
- Integration tests for key rotation, token expiry, and refresh flows
Monthly: Run a full crypto audit using the processes in this guide. Document findings, assign ownership, track remediation.
When Incidents Happen: Treat crypto vulnerabilities as critical. They don’t affect just one user—they affect security guarantees for the entire system. Response should be immediate.
Summary
Cryptographic security isn’t magic, and it’s not something you need to understand at a PhD level to audit it effectively. You need to:
- Know the red flags: Weak algorithms, bad key management, insecure RNG, TLS misconfiguration
- Understand the context: Why MD5 is fine for checksums but catastrophic for passwords
- Know the right alternatives: Argon2 instead of SHA-256, AES-GCM instead of AES-CBC
- Automate the search: Let tools find patterns; focus on understanding implications
- Build review into process: Cryptography isn’t a security add-on; it’s foundational
- Rotate keys regularly: Schedule this like you schedule backups—because it’s equally critical
- Train your team: A security culture beats a security tool
- Respond quickly: When vulnerabilities are found, treat them as the emergencies they are
Use Claude Code to systematically audit your cryptographic implementations. It catches what static analysis misses and what code review usually overlooks. Your future self—and your users—will thank you.
The key insight: cryptographic vulnerabilities don’t announce themselves. They hide until attackers find them. Systematic review finds them first. By building this review into your normal workflow, you shift from discovering breaches in production to preventing them in development.
-iNet
Systematic security review that actually catches the vulnerabilities that matter.