The security toolkit explained properly
From entropy math to the Web Crypto API to k-anonymity breach checking, SSL/TLS grading, security headers, AES-GCM encryption, JWT attacks, and CORS — the concepts behind every ShieldX tool, with working code examples you can verify yourself.
- 20 fundamentals
- 36 tool guides
- NIST-aligned
- Fundamentals
- 20
- Tool guides
- 36
- Client-side
- 100%
Security fundamentals
20 foundational chapters covering the theory behind every tool. Browse by category, click any card to read.
Guides for every tool
36 interactive guides — one for each tool. Click Preview for a quick summary, or Read guide for the full page.
Password Strength Checker
Entropy-based scoring with NIST SP 800-63B compliance
SSL Certificate Checker
Inspect certificate chains, protocols, and cipher strength
Base64 Encoder / Decoder
UTF-8 safe encoding and decoding, including URL-safe variant
Secret / API Key Generator
Secure API keys and tokens using crypto.getRandomValues()
Try the tools right now
Every concept in this guide is implemented in ShieldX. Open a tool, watch the network tab stay empty, and verify the entropy math yourself.
No signup · No cookies · No cost · secure.toolly.site
Password Generator
Cryptographically secure passwords using the Web Crypto API
What is a secure password generator?
A secure password generator produces random strings using a cryptographically secure pseudo-random number generator (CSPRNG) rather than Math.random(). The Web Crypto API exposes the operating system's entropy source through crypto.getRandomValues(), giving you the same class of randomness used by TLS connections.
The key difference: Math.random() is seeded from a predictable source and uses a simple PRNG algorithm. If an attacker knows the seed, they can reproduce every "random" value. crypto.getRandomValues() draws from the OS entropy pool, which collects noise from hardware interrupts, keystroke timing, and other physical sources.
// ❌ Never use Math.random() for passwords
const weak = Math.random().toString(36).slice(2);
// ✅ Always use crypto.getRandomValues()
function securePassword(length: number, charset: string): string {
const array = new Uint32Array(length);
crypto.getRandomValues(array);
return Array.from(array, (n) => charset[n % charset.length]).join('');
}
Understanding entropy and charset
Entropy is measured in bits and calculated as log2(charset^length). A 16-character password using 62 symbols (a–z, A–Z, 0–9) yields ~95 bits of entropy. Adding special characters (94 charset) at 16 characters gives ~105 bits.
Charset sizes at a glance
- Lowercase only (a–z): 26 symbols
- Alphanumeric (a–z, A–Z, 0–9): 62 symbols
- Full keyboard (incl. special chars): 94 symbols
- Hexadecimal (0–9, a–f): 16 symbols
TipDoubling password length doubles entropy. Doubling charset adds only 1 bit per character. Length wins every time.
Avoiding modulo bias
A common mistake is using modulo to map random bytes to charset indices. If the charset has 62 characters and you generate a random value 0–255, values 0–247 map evenly (4 each), but values 248–255 map to indices 0–7 — giving those characters a slightly higher probability.
WarningModulo bias is small but real. For passwords, even a slight bias reduces the effective entropy. The correct approach is rejection sampling: discard values that would cause bias.
// Rejection sampling to eliminate modulo bias
function unbiasedIndex(charsetLen: number): number {
const max = 256 - (256 % charsetLen);
const arr = new Uint8Array(1);
do {
crypto.getRandomValues(arr);
} while (arr[0] >= max);
return arr[0] % charsetLen;
}
Password Strength Checker
Entropy-based scoring with NIST SP 800-63B compliance
Why most strength checkers are wrong
Most password strength checkers use simple heuristics: length thresholds, character class requirements, and regex patterns. These approaches reward "Password1!" as strong because it has uppercase, lowercase, a digit, and a special character — but it would be cracked in seconds.
A proper strength checker calculates actual entropy: log2(charset^length), then estimates crack time based on realistic hash rates. It also checks against NIST SP 800-63B guidance, which moved away from forced complexity toward length and unpredictability.
NIST SP 800-63B key recommendations
NIST Special Publication 800-63B (2017, updated 2020) replaced the old complexity rules with evidence-based requirements. The key changes:
- Minimum 8 characters, with support for long passwords (≥64 chars)
- No mandatory composition rules (no "must contain uppercase + symbol")
- Screen against known compromised passwords (breach lists)
- Allow paste and password managers
- No password hints or knowledge-based authentication
TipNIST explicitly states that composition rules make passwords harder to remember without making them harder to crack. Length and randomness are what matter.
Estimating crack time realistically
Crack time is estimated by dividing the keyspace (2^entropy) by the attack rate. Modern GPUs can test ~100 billion hashes/second for fast hashes like SHA-256. For bcrypt with cost factor 12, the rate drops to ~100/second.
function crackTime(entropyBits: number, hashRate: number): string {
const guesses = Math.pow(2, entropyBits) / 2; // average = half the keyspace
const seconds = guesses / hashRate;
if (seconds < 1) return 'instant';
if (seconds < 60) return `${Math.round(seconds)} seconds`;
if (seconds < 3600) return `${Math.round(seconds / 60)} minutes`;
// ... scale up to years, centuries, millennia
}
WarningCrack time estimates assume offline attacks where the attacker has the hash. Online attacks are rate-limited and much slower, but you should always design for the worst case.
Breach Checker
K-anonymity breach checking with Have I Been Pwned
What is k-anonymity?
K-anonymity is a privacy model that ensures you cannot be distinguished from at least k-1 other individuals. In the context of breach checking, ShieldX uses the Have I Been Pwned (HIBP) API with a k-anonymity model: only the first 5 characters of your password's SHA-1 hash are sent to the server.
With 5 hex characters, there are 16^5 = 1,048,576 possible prefixes. The server returns all breach entries matching that prefix — potentially hundreds of hashes. Your full hash is compared locally, so the server never knows which specific password you checked.
Step-by-step: checking a password safely
- SHA-1 hash the password locally in your browser
- Take the first 5 characters of the hex hash
- Send only those 5 characters to the HIBP API
- Receive all matching hash suffixes with breach counts
- Compare your full hash locally against the returned list
- Report the breach count if matched, nothing otherwise
async function checkBreach(password: string): Promise<number> {
// 1. Hash locally
const data = new TextEncoder().encode(password);
const hashBuf = await crypto.subtle.digest('SHA-1', data);
const fullHash = [...new Uint8Array(hashBuf)]
.map((b) => b.toString(16).padStart(2, '0')).join('');
// 2. Send only first 5 chars
const prefix = fullHash.slice(0, 5).toUpperCase();
const res = await fetch(
`https://api.pwnedpasswords.com/range/${prefix}`
);
const text = await res.text();
// 3. Compare locally
const suffix = fullHash.slice(5).toUpperCase();
const match = text
.split('\n')
.find((line) => line.startsWith(suffix));
return match ? parseInt(match.split(':')[1]) : 0;
}
Why this is safe
TipThe server sees only a 5-character prefix shared by ~1 million other hashes. It cannot determine your password, your full hash, or even if your password was found in a breach.
WarningNever send your plaintext password to any breach checking service. Always verify that the tool hashes locally first — you can check the network tab to confirm only the hash prefix is transmitted.
Passphrase Generator
EFF Diceware passphrases with real entropy
Why passphrases beat passwords
Passphrases use multiple random words instead of random characters. "correct-horse-battery-staple" has 44 bits of entropy from 4 words, but is far easier to remember than "Tr0ub4dor&3" which has roughly the same strength. The human brain remembers sequences of meaningful words much better than arbitrary character strings.
The EFF Diceware word list contains 7,776 words (6^5). Each word selected by rolling 5 dice contributes log2(7776) ≈ 12.9 bits of entropy. Six words give ~77 bits — stronger than most passwords and far more memorable.
The EFF Diceware word list
The Electronic Frontier Foundation published a curated word list specifically designed for passphrase generation. Unlike the original Diceware list, the EFF list avoids words that are similar to each other, contain special characters, or are particularly difficult to remember.
- 7,776 words = 6^5 (five six-sided dice)
- Each word adds ~12.9 bits of entropy
- 4 words = ~52 bits (good for everyday use)
- 6 words = ~77 bits (recommended for sensitive accounts)
- 8 words = ~103 bits (cryptographic strength)
TipUse a separator that's easy to type but uncommon in natural language. Hyphens, spaces, or periods all work. Avoid using the same separator you use elsewhere.
CSPRNG word selection
function pickWord(wordlist: string[], rng: (max: number) => number): string {
// Rejection sampling to avoid modulo bias
const max = Math.floor(0xFFFFFFFF / wordlist.length) * wordlist.length;
let n: number;
do {
const arr = new Uint32Array(1);
crypto.getRandomValues(arr);
n = arr[0];
} while (n >= max);
return wordlist[n % wordlist.length];
}
WarningNever use Math.random() to select passphrase words. A predictable RNG means an attacker who knows your generation algorithm can reproduce your entire passphrase.
SSL Certificate Checker
Inspect certificate chains, protocols, and cipher strength
What an SSL certificate tells you
An SSL/TLS certificate is a digital file that binds a domain name to a cryptographic key pair. When you visit an HTTPS site, the server presents its certificate, and your browser verifies it against a chain of trust leading back to a Certificate Authority (CA) root.
A certificate contains: the domain name (CN/SAN), issuing CA, validity period, public key, signature algorithm, and the chain of intermediate certificates. Checking all of these reveals misconfigurations, weak keys, and imminent expirations.
A+ to F grading system
ShieldX grades certificates based on multiple factors:
- Protocol version: TLS 1.3 > TLS 1.2 > TLS 1.1 (deprecated) > SSL (insecure)
- Key length: RSA 4096 > RSA 2048 > RSA 1024 (weak) > RSA 512 (broken)
- Cipher suites: AEAD (GCM, ChaCha20) > CBC > RC4 (insecure)
- Forward secrecy: ECDHE/DHE required for A grade
- HSTS presence: required for A+
WarningA certificate can be valid but still use weak protocols. Always check the protocol version and cipher suite, not just the validity dates.
Certificate chain validation
A certificate chain starts with the server certificate, links through one or more intermediate CAs, and ends at a root CA trusted by the browser. If any link is missing, broken, or uses a weak signature, the chain is invalid.
TipThe most common misconfiguration is a missing intermediate certificate. This works in browsers that cache intermediates but fails in fresh connections from bots, APIs, or mobile apps.
Security Headers Scanner
Audit CSP, HSTS, X-Frame-Options and more
Why security headers matter
HTTP security headers are your first line of defense against client-side attacks. They instruct the browser to enforce policies that prevent XSS, clickjacking, MIME-type sniffing, and downgrade attacks. A site without security headers is leaving easy wins on the table.
ShieldX scans for all major security headers and provides a posture score from 0–100 based on which headers are present and correctly configured.
The essential security headers
Content-Security-Policy (CSP)
The most powerful header. CSP restricts which resources can load and execute, preventing XSS at the browser level. A strong CSP uses nonces or hashes instead of unsafe-inline.
Strict-Transport-Security (HSTS)
Forces HTTPS for all future visits. Without HSTS, a user who types "example.com" is vulnerable to a TLS downgrade attack on the first request.
X-Frame-Options / frame-ancestors
Prevents your site from being embedded in iframes, blocking clickjacking attacks. CSP frame-ancestors supersedes X-Frame-Options.
WarningSetting X-Frame-Options to DENY will break legitimate iframe embeds. Use CSP frame-ancestors with specific origins if you need selective embedding.
How the posture score works
- CSP with no unsafe-inline: +25 points
- HSTS with max-age ≥ 1 year: +20 points
- X-Content-Type-Options: nosniff: +10 points
- X-Frame-Options or frame-ancestors: +15 points
- Referrer-Policy: +10 points
- Permissions-Policy: +10 points
- Cross-Origin headers (COOP/COEP/CORP): +10 points
TipStart with HSTS and X-Content-Type-Options — they have zero risk of breaking your site. Then layer in CSP carefully, testing as you tighten.
DNS Lookup
Query every record type over DNS-over-HTTPS
DNS record types explained
The Domain Name System (DNS) is the phonebook of the internet. It translates domain names into IP addresses and stores various metadata. Each record type serves a different purpose:
- A: Maps a domain to an IPv4 address
- AAAA: Maps a domain to an IPv6 address
- CNAME: Alias from one domain to another
- MX: Mail exchange servers for the domain
- TXT: Arbitrary text (SPF, DKIM, verification tokens)
- NS: Authoritative name servers
- SOA: Start of authority (admin info, serial, TTLs)
- CAA: Certificate Authority Authorization
- SRV: Service records (port, priority, weight)
- PTR: Reverse DNS (IP → domain)
DNS-over-HTTPS (DoH)
Traditional DNS queries are sent in plaintext over UDP port 53, making them visible to anyone on the network. DNS-over-HTTPS encrypts queries inside HTTPS requests, providing privacy and preventing tampering.
TipShieldX uses Cloudflare's DoH endpoint (1.1.1.1) by default, with options for Google (8.8.8.8) and Quad9 (9.9.9.9). All queries are encrypted and cannot be inspected by your ISP.
DNSSEC validation
DNSSEC adds cryptographic signatures to DNS records, allowing resolvers to verify that responses are authentic and unmodified. Without DNSSEC, DNS responses can be spoofed by a man-in-the-middle.
WarningDNSSEC must be enabled at the domain registrar and configured in your DNS provider. A misconfigured DNSSEC setup can make your domain completely unreachable — always test after enabling.
DMARC/SPF/DKIM Checker
Email authentication: SPF, DKIM, and DMARC
The three pillars of email authentication
Email spoofing is trivial without authentication. SPF, DKIM, and DMARC work together to verify that an email actually came from the domain it claims to be from. Each handles a different aspect of the problem.
- SPF: Which IP addresses are allowed to send mail for this domain
- DKIM: Cryptographic signature proving the email wasn't modified
- DMARC: Policy for what to do when SPF or DKIM fails
SPF (Sender Policy Framework)
SPF is a TXT record that lists the mail servers authorized to send email from your domain. When a receiving server gets mail claiming to be from you, it checks your SPF record to see if the sending IP is listed.
; Basic SPF record
example.com. TXT "v=spf1 ip4:192.0.2.0/24 include:_spf.google.com ~all"
; v=spf1 — SPF version
; ip4: — authorize this IP range
; include: — inherit another domain's SPF
; ~all — soft fail (mark but accept)
; -all — hard fail (reject)
; +all — allow anything (don't do this)
WarningSPF has a 10-DNS-lookup limit. Each include: counts as one lookup. If you chain too many includes, receivers will stop evaluating and treat the email as unauthorized.
DKIM (DomainKeys Identified Mail)
DKIM adds a digital signature to each email using a private key. The public key is published in DNS. Receiving servers verify the signature to confirm the email wasn't modified in transit.
TipRotate DKIM keys annually. If a private key is compromised, an attacker can sign emails that pass DKIM verification. Key rotation limits the window of exposure.
DMARC (Domain-based Message Authentication)
DMARC ties SPF and DKIM together with a policy. It tells receivers what to do when authentication fails: do nothing (p=none), quarantine (p=quarantine), or reject (p=reject). Start with p=none and aggregate reports to monitor, then escalate.
; Start with monitoring mode
_dmarc.example.com. TXT "v=DMARC1; p=none; rua=mailto:dmarc@example.com; ruf=mailto:dmarc@example.com; fo=1; adkim=s; aspf=s"
; Escalate to quarantine after monitoring
_dmarc.example.com. TXT "v=DMARC1; p=quarantine; pct=50; rua=mailto:dmarc@example.com"
; Final: reject all unauthenticated mail
_dmarc.example.com. TXT "v=DMARC1; p=reject; rua=mailto:dmarc@example.com"
TipThe pct= parameter lets you roll out DMARC gradually. Start at pct=10 with p=quarantine, monitor the reports, and increase to 100% before switching to p=reject.
CORS Checker
Check Access-Control-* headers and misconfigurations
What is CORS?
Cross-Origin Resource Sharing (CORS) is a browser security mechanism that controls when JavaScript on one origin can make requests to a different origin. Without CORS, the same-origin policy would block all cross-origin requests.
CORS is not a security feature — it's a relaxation of security. The same-origin policy protects users by default. CORS headers tell the browser to allow specific cross-origin requests that would otherwise be blocked.
Key CORS headers
- Access-Control-Allow-Origin: Which origins can read the response
- Access-Control-Allow-Methods: Permitted HTTP methods
- Access-Control-Allow-Headers: Permitted request headers
- Access-Control-Allow-Credentials: Whether cookies/auth are sent
- Access-Control-Max-Age: How long to cache preflight results
WarningAccess-Control-Allow-Origin: * combined with Access-Control-Allow-Credentials: true is invalid and browsers will reject it. You must specify exact origins when credentials are involved.
Common CORS misconfigurations
The most dangerous CORS misconfiguration is reflecting the Origin header back as the ACAO value with credentials enabled. This allows any website to make authenticated requests to your API.
- Reflecting Origin header → any site can read responses
- Wildcard with credentials → browsers block it (but some servers misbehave)
- Overly broad origin patterns (e.g., *.example.com matching evil.example.com)
- Allowing unnecessary methods (DELETE, PUT) on read-only endpoints
TipMaintain an explicit allowlist of origins. Never reflect the Origin header. If you need dynamic origins, validate against a known list before returning the ACAO header.
HSTS Checker
Verify Strict-Transport-Security headers
What is HSTS?
HTTP Strict-Transport-Security (HSTS) tells browsers to only connect via HTTPS for a specified period. Without HSTS, the first request to a site is sent over HTTP and can be intercepted before the redirect to HTTPS occurs.
HSTS is especially important for users who type "example.com" directly — the browser defaults to HTTP, creating a vulnerability window on every first visit.
HSTS directives
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
; max-age=31536000 — 1 year in seconds
; includeSubDomains — apply to all subdomains
; preload — opt into browser HSTS preload lists
WarningEnabling includeSubDomains affects every subdomain. If you have a subdomain that must run on HTTP (e.g., an internal tool), do not use includeSubDomains.
HSTS preloading
The HSTS preload list is built into browsers (Chrome, Firefox, Safari). Domains on this list are forced to HTTPS before the first request is ever made, eliminating the initial HTTP vulnerability entirely.
TipBefore submitting to the preload list, ensure all subdomains work over HTTPS. Once preloaded, removal takes months — you cannot quickly undo it.
Cookie Analyzer
Parse Set-Cookie headers and audit security flags
Cookie security flags
Cookies are small key-value pairs stored by the browser. Without security flags, they can be stolen over HTTP, read by JavaScript, or sent to third-party sites. Three flags protect against these threats:
- Secure: Cookie is only sent over HTTPS
- HttpOnly: JavaScript cannot access the cookie (prevents XSS theft)
- SameSite: Controls when cookies are sent cross-site (prevents CSRF)
SameSite attribute deep dive
SameSite controls cross-site cookie transmission:
- SameSite=Strict: Cookie only sent in first-party contexts (same site)
- SameSite=Lax: Cookie sent on top-level navigations from external sites (default in modern browsers)
- SameSite=None: Cookie sent in all cross-site requests (requires Secure)
WarningSameSite=None without Secure will be rejected by modern browsers. If you need cross-site cookies (e.g., third-party embeds), you must set both SameSite=None and Secure.
Security scoring
ShieldX scores each cookie based on which flags are present. A cookie with all three flags (Secure + HttpOnly + SameSite=Strict/Lax) gets a perfect score. Session cookies without Secure or HttpOnly are flagged as critical.
TipSession cookies should always have HttpOnly and Secure. SameSite=Lax is the minimum recommended; use Strict for sensitive session cookies that don't need cross-site navigation.
Redirect Chain Checker
Trace redirect hops and detect loops
Understanding HTTP redirects
HTTP redirects (301, 302, 307, 308) send browsers from one URL to another. Redirect chains occur when multiple redirects happen in sequence: A → B → C → D. Each hop adds latency and potential failure points.
- 301: Permanent redirect (cached by browsers)
- 302: Temporary redirect (not cached by default)
- 307: Temporary redirect, preserves HTTP method
- 308: Permanent redirect, preserves HTTP method
Common redirect problems
- Redirect loops: A → B → A (browser gives up after ~20 hops)
- HTTP→HTTPS chains: http:// → https:// → www.https:// (should be one hop)
- Lost query parameters: some redirects strip the query string
- Broken final destination: chain ends at a 404
TipIdeal redirect chains are 0–1 hops. If your canonical URL is https://example.com, both http:// and http://www. should redirect directly there in a single hop.
WHOIS Lookup
Query domain registration info via RDAP
WHOIS vs RDAP
WHOIS is the traditional protocol for querying domain registration data. RDAP (Registration Data Access Protocol) is its modern replacement, offering structured JSON responses and better support for internationalized domains.
ShieldX uses RDAP because it provides machine-readable data, supports rate limiting, and is the IETF standard. Legacy WHOIS returns unstructured text that varies by registrar.
Key registration fields
- Registrar: The company that sold the domain
- Creation date: When the domain was first registered
- Expiration date: When the registration expires
- Name servers: DNS servers for the domain
- Status: Registration status codes (clientTransferProhibited, etc.)
TipDomain age is a trust signal. Newly registered domains (less than 30 days) are often associated with phishing or spam. Check the creation date before trusting an unfamiliar site.
Subdomain Finder
Discover subdomains via Certificate Transparency
Certificate Transparency logs
Certificate Transparency (CT) is a system where CAs publicly log every certificate they issue. These logs are publicly queryable, making them a goldmine for subdomain enumeration — every certificate includes the domain names it covers.
ShieldX queries crt.sh, which indexes CT logs and provides a searchable interface. This is passive enumeration: no packets are sent to the target domain, making it safe and undetectable.
Subdomain takeover risks
Subdomain takeover occurs when a subdomain points to a decommissioned third-party service (e.g., an old GitHub Pages, Heroku, or S3 endpoint). An attacker can claim the orphaned resource and serve content on your subdomain.
WarningIf you find subdomains pointing to services you no longer use, remove the DNS records immediately. A takeover can be used for phishing, stealing cookies via same-origin policies, or damaging your brand.
Port Scanner
Check open TCP ports and identify exposed services
Port scanning fundamentals
Every service on a server listens on a specific TCP or UDP port. Port scanning probes these ports to determine which services are exposed. This is essential for attack surface management — you can't secure what you don't know exists.
- Port 22: SSH (secure shell)
- Port 80: HTTP
- Port 443: HTTPS
- Port 3306: MySQL
- Port 5432: PostgreSQL
- Port 6379: Redis
- Port 27017: MongoDB
Securing exposed ports
WarningDatabase ports (3306, 5432, 6379, 27017) should never be exposed to the public internet. Use a firewall to restrict access to trusted IPs only, or require a VPN/SSH tunnel.
TipRun ShieldX's port scanner against your own servers regularly. Close any ports that don't need to be public, and move management interfaces behind a VPN.
IP Address Lookup
Geolocate IPs, find ISP, ASN, and abuse contacts
What IP geolocation reveals
IP geolocation maps an IP address to a physical location (country, region, city), along with the ISP, Autonomous System Number (ASN), and abuse contact. This is useful for fraud detection, log analysis, and network troubleshooting.
Geolocation is approximate — it typically identifies the ISP's point of presence, not the exact device. City-level accuracy ranges from 50–90% depending on the region and ISP.
Autonomous Systems (ASN)
An ASN is a unique identifier for a group of IP networks under a single administrative policy. Large companies (Google, Amazon, Cloudflare) have their own ASNs. Knowing the ASN helps identify traffic sources and detect VPN/proxy usage.
TipIf you're investigating suspicious traffic, the ASN tells you which hosting provider to contact. The abuse contact email is usually listed in the RDAP/WHOIS record for the IP range.
CVSS Calculator
Calculate CVSS v3.1 base scores interactively
What is CVSS?
The Common Vulnerability Scoring System (CVSS) is a standardized method for rating vulnerability severity. CVSS v3.1 is the current version, producing a score from 0.0 to 10.0 based on exploitability and impact metrics.
The score is calculated from a vector string that encodes all metric values. ShieldX lets you adjust each metric interactively and see the score update in real time.
Base score metrics
Exploitability metrics
- Attack Vector (AV): Network / Adjacent / Local / Physical
- Attack Complexity (AC): Low / High
- Privileges Required (PR): None / Low / High
- User Interaction (UI): None / Required
- Scope (S): Unchanged / Changed
Impact metrics
- Confidentiality (C): None / Low / High
- Integrity (I): None / Low / High
- Availability (A): None / Low / High
TipA CVSS score of 7.0+ means High severity. Scores of 9.0+ are Critical. Prioritize remediation based on score, but also consider exploit availability and your specific environment.
Understanding the vector string
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H
; AV:N — Attack Vector: Network
; AC:L — Attack Complexity: Low
; PR:N — Privileges Required: None
; UI:N — User Interaction: None
; S:U — Scope: Unchanged
; C:H — Confidentiality: High
; I:H — Integrity: High
; A:H — Availability: High
; Score: 9.8 (Critical)
Mixed Content Checker
Detect HTTP resources on HTTPS pages
What is mixed content?
Mixed content occurs when an HTTPS page loads resources (images, scripts, stylesheets) over HTTP. Browsers block active mixed content (scripts, iframes) entirely and warn about passive mixed content (images, audio).
Mixed content breaks the security guarantee of HTTPS — an attacker on the network can modify the HTTP resources, potentially injecting malicious scripts or replacing content.
Fixing mixed content
- Replace http:// with https:// in all resource URLs
- Use protocol-relative URLs (//example.com/asset.js) — not recommended
- Add a CSP upgrade-insecure-requests directive as a safety net
- Use HSTS to prevent initial HTTP requests
TipThe CSP directive upgrade-insecure-requests automatically rewrites HTTP requests to HTTPS. It's a great temporary fix while you hunt down hardcoded HTTP URLs in your codebase.
CAA Record Checker
Check Certificate Authority Authorization records
What is CAA?
CAA (Certificate Authority Authorization) is a DNS record that specifies which CAs are allowed to issue certificates for your domain. Without CAA, any CA can issue a certificate for any domain — if one CA is compromised, your domain is at risk.
CAA creates a whitelist: only the CAs you explicitly list can issue certificates. All others must refuse. This limits the blast radius of a CA compromise.
Configuring CAA records
; Allow only Let's Encrypt to issue certificates
example.com. CAA 0 issue "letsencrypt.org"
; Allow wildcard certificates from Let's Encrypt
example.com. CAA 0 issuewild "letsencrypt.org"
; Send violation reports to this email
example.com. CAA 0 iodef "mailto:security@example.com"
; Block all certificate issuance (use with caution)
example.com. CAA 0 issue ";"
WarningSetting issue to ";" blocks all certificate issuance. If you do this by accident, your certificates cannot be renewed, and your site will go offline when the current cert expires.
Domain Age Checker
Check domain registration age from RDAP data
Why domain age matters
Domain age — the time since a domain was first registered — is a useful trust signal. Legitimate businesses typically have domains registered years ago, while phishing and scam sites often use domains registered days or weeks before an attack.
ShieldX queries RDAP to find the creation date and calculates the age in years, months, and days. It also shows the expiration date and a countdown if the domain is nearing expiry.
Using domain age for trust assessment
- < 30 days: High risk — likely newly created for a specific campaign
- 30–90 days: Moderate risk — common for legitimate new businesses
- 1–5 years: Low risk — established but not necessarily reputable
- 5+ years: Very low risk — domain has persisted over time
TipDomain age is one signal among many. A 10-year-old domain can still host malware if it was compromised. Combine with SSL checks, security headers, and breach data for a complete picture.
Hash Generator
MD5 through SHA-512 plus HMAC signing, all in-browser
Cryptographic hash functions
A hash function takes input of any size and produces a fixed-size output (digest). Cryptographic hash functions have three key properties: pre-image resistance (you can't reverse the hash), second pre-image resistance (you can't find a different input with the same hash), and collision resistance (you can't find any two inputs with the same hash).
- MD5 (128-bit): Broken — do not use for security
- SHA-1 (160-bit): Broken — deprecated by all major CAs
- SHA-256 (256-bit): Secure, widely used
- SHA-384 (384-bit): Secure, used in TLS
- SHA-512 (512-bit): Secure, high-performance on 64-bit CPUs
Hashing with the Web Crypto API
// Hash text
async function hashText(text: string, algo: string): Promise<string> {
const data = new TextEncoder().encode(text);
const buf = await crypto.subtle.digest(algo, data);
return [...new Uint8Array(buf)]
.map((b) => b.toString(16).padStart(2, '0')).join('');
}
// Hash a file
async function hashFile(file: File, algo: string): Promise<string> {
const buf = await file.arrayBuffer();
const digest = await crypto.subtle.digest(algo, buf);
return [...new Uint8Array(digest)]
.map((b) => b.toString(16).padStart(2, '0')).join('');
}
WarningNever use MD5 or SHA-1 for password hashing, integrity checking, or digital signatures. They have known collisions. Use SHA-256 at minimum, or bcrypt/Argon2 for passwords.
When to use each algorithm
- File integrity verification: SHA-256 or SHA-512
- Git-style content addressing: SHA-256
- Password storage: bcrypt or Argon2 (not plain hashes)
- HMAC signatures: SHA-256 or SHA-512
- Certificate signatures: SHA-256 or SHA-384
TipFor password storage, never use a plain hash — even SHA-512. Use bcrypt, scrypt, or Argon2 which are designed to be slow and resist brute-force attacks.
UUID Generator
RFC 4122 v4 and v7 identifiers in bulk
UUID versions explained
A UUID (Universally Unique Identifier) is a 128-bit identifier that doesn't require central coordination. Different UUID versions use different strategies to ensure uniqueness:
- UUID v1: Time-based + MAC address (privacy concern)
- UUID v4: Random (122 bits of entropy from CSPRNG)
- UUID v7: Time-ordered (timestamp + random) — sortable!
UUID v7 is the modern choice for databases — it's time-ordered so records sort chronologically, and it avoids the index fragmentation that random v4 UUIDs cause in B-tree indexes.
Generating UUIDs in the browser
// UUID v4 — crypto.randomUUID() is built into modern browsers
const id = crypto.randomUUID();
// → "f47ac10b-58cc-4372-a567-0e02b2c3d479"
// UUID v7 — time-ordered (requires manual implementation)
function uuidv7(): string {
const ts = Date.now();
const ms = ts >> 16;
const arr = new Uint8Array(16);
crypto.getRandomValues(arr);
// Set version (7) and variant bits
arr[6] = (arr[6] & 0x0f) | 0x70;
arr[8] = (arr[8] & 0x3f) | 0x80;
// ... format as UUID string with timestamp prefix
}
Tipcrypto.randomUUID() is available in all modern browsers and Node.js 19+. It generates UUID v4 using the same CSPRNG as crypto.getRandomValues().
Random Number Generator
Uniform, bias-free random values from real entropy
True randomness vs pseudo-randomness
Math.random() uses a PRNG (pseudo-random number generator) with a predictable seed. It's fine for UI animations and games, but not for security, cryptography, or fair lotteries. crypto.getRandomValues() uses the OS entropy pool, which collects true randomness from hardware.
ShieldX generates random numbers using crypto.getRandomValues() with rejection sampling to eliminate modulo bias, Fisher-Yates shuffle for list randomization, and simulated dice rolls from D4 to D100.
Fisher-Yates shuffle
function shuffle<T>(arr: T[]): T[] {
const result = [...arr];
for (let i = result.length - 1; i > 0; i--) {
// Unbiased random index 0..i
const max = Math.floor(0xFFFFFFFF / (i + 1)) * (i + 1);
let n: number;
do {
const buf = new Uint32Array(1);
crypto.getRandomValues(buf);
n = buf[0];
} while (n >= max);
const j = n % (i + 1);
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
TipThe Fisher-Yates shuffle is O(n) and produces a truly uniform permutation. Using Math.random() for shuffling introduces a subtle bias — some permutations are more likely than others.
Base64 Encoder / Decoder
UTF-8 safe encoding and decoding, including URL-safe variant
What is Base64?
Base64 encodes binary data as ASCII text using 64 characters (A–Z, a–z, 0–9, +, /). It's used to embed binary data in JSON, HTML, CSS, and URLs where raw binary would be corrupted. Every 3 bytes of input become 4 characters of output.
The URL-safe variant replaces + with - and / with _, and omits padding. This is used in JWTs, data URLs, and anywhere the standard Base64 characters would be misinterpreted by URL parsers.
The Unicode pitfall
A common bug: using btoa() with non-ASCII text. btoa() only accepts Latin1 characters. Encoding "café" or "日本語" will throw an error or produce garbage.
// ❌ Throws on non-ASCII
btoa('café'); // Error
// ✅ Encode UTF-8 first, then Base64
function encodeBase64(str: string): string {
const bytes = new TextEncoder().encode(str);
return btoa(String.fromCharCode(...bytes));
}
// ✅ Decode Base64 back to UTF-8
function decodeBase64(b64: string): string {
const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
WarningBase64 is encoding, not encryption. Anyone can decode it. Never use Base64 to "hide" sensitive data — it's trivially reversible.
JWT Decoder
Decode JWTs, detect alg:none attacks, validate expiry
JWT structure
A JSON Web Token (JWT) has three parts: header.payload.signature, each Base64URL-encoded. The header specifies the algorithm, the payload contains claims, and the signature proves integrity.
// Header
{ "alg": "HS256", "typ": "JWT" }
// Payload
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022,
"exp": 1516242622
}
// Signature
HMAC-SHA256(base64(header) + "." + base64(payload), secret)
The alg:none attack
The most critical JWT vulnerability: if a server trusts the algorithm specified in the token header, an attacker can set "alg": "none" and remove the signature. The server skips verification and accepts the forged payload.
WarningNever trust the alg field from the token. Always specify the expected algorithm on the server side and reject tokens with alg:none. ShieldX flags any JWT using alg:none as a critical security risk.
Standard claims to check
- exp (expiration): Reject expired tokens
- nbf (not before): Reject tokens used before their start time
- iat (issued at): Check for unreasonable timestamps
- iss (issuer): Verify the token came from your auth server
- aud (audience): Verify the token was issued for your service
TipJWTs are not encrypted — the payload is Base64-encoded, not encrypted. Never store sensitive data in a JWT payload unless you're using JWE (encrypted tokens).
HMAC Generator
HMAC-SHA256/384/512 signatures with the Web Crypto API
What is HMAC?
HMAC (Hash-based Message Authentication Code) combines a hash function with a secret key to produce a signature. Unlike a plain hash, an attacker cannot forge an HMAC without knowing the secret key. This makes HMAC ideal for API authentication and webhook verification.
HMAC-SHA256 is the most common variant, used by AWS SigV4, GitHub webhooks, and JWT signing. ShieldX supports SHA-256, SHA-384, and SHA-512 using the Web Crypto API.
Generating HMACs in the browser
async function hmac(
message: string,
secret: string,
algo: 'SHA-256' | 'SHA-384' | 'SHA-512'
): Promise<string> {
const keyData = new TextEncoder().encode(secret);
const msgData = new TextEncoder().encode(message);
const key = await crypto.subtle.importKey(
'raw', keyData, { name: 'HMAC', hash: algo }, false, ['sign']
);
const sig = await crypto.subtle.sign('HMAC', key, msgData);
return [...new Uint8Array(sig)]
.map((b) => b.toString(16).padStart(2, '0')).join('');
}
TipFor webhook verification, use constant-time comparison when checking the HMAC. A normal string comparison can leak timing information that reveals the correct signature character by character.
URL Encoder / Decoder
Percent-encoding and decoding with full Unicode safety
URL encoding basics
URLs can only contain ASCII characters. Special characters like spaces, ampersands, and non-ASCII text must be percent-encoded. A space becomes %20 or +, an ampersand becomes %26, and "café" becomes "caf%C3%A9".
JavaScript provides two functions: encodeURIComponent() encodes individual URL components, while encodeURI() preserves URL-structural characters like : and /.
encodeURIComponent vs encodeURI
// encodeURIComponent — for query params, path segments
encodeURIComponent('hello world & friends');
// → "hello%20world%20%26%20friends"
// encodeURI — for full URLs (preserves :, /, ?, &, =)
encodeURI('https://example.com/path?q=hello world');
// → "https://example.com/path?q=hello%20world"
// decodeURIComponent — reverses encodeURIComponent
decodeURIComponent('hello%20world');
// → "hello world"
WarningNever use encodeURI for query parameter values — it won't encode & or =, which can break the URL structure. Use encodeURIComponent for individual values.
Hash Identifier
Detect hash types by length and format
How hash identification works
Hash identification uses the length, character set, and format of a hash to guess the algorithm. MD5 is always 32 hex characters, SHA-256 is 64 hex characters, bcrypt always starts with $2a$, $2b$, or $2y$.
- MD5: 32 hex chars
- SHA-1: 40 hex chars
- SHA-256: 64 hex chars
- SHA-384: 96 hex chars
- SHA-512: 128 hex chars
- bcrypt: starts with $2a$/$2b$/$2y$, 60 chars
- Argon2: starts with $argon2
- NTLM: 32 hex chars (same as MD5 — ambiguous)
Limitations of hash identification
Hash identification is probabilistic, not definitive. Some hashes share the same length (MD5 and NTLM are both 32 hex chars). Base64-encoded hashes have different lengths than hex-encoded ones. Custom or salted hashes may not match any known pattern.
TipShieldX provides a confidence score for each match. Multiple possible matches are listed with their probabilities, so you can make an informed decision.
Bcrypt Generator
Generate and compare bcrypt hashes with adjustable cost
Why bcrypt for passwords?
Bcrypt is a password hashing function designed specifically to be slow. Unlike SHA-256 which can be computed millions of times per second on a GPU, bcrypt with cost factor 12 takes ~250ms per hash — making brute-force attacks economically impractical.
Bcrypt also has a built-in salt, so identical passwords produce different hashes. This prevents rainbow table attacks and ensures that compromising one user's hash doesn't reveal others with the same password.
Understanding the cost factor
The cost factor (also called work factor) determines how many rounds of the key derivation function are applied. The cost is exponential: cost 10 takes 2^10 = 1,024 rounds, cost 12 takes 2^12 = 4,096 rounds, cost 14 takes 2^14 = 16,384 rounds.
- Cost 10: ~64ms — minimum acceptable
- Cost 12: ~250ms — recommended for most applications
- Cost 14: ~1s — high-security applications
- Cost 16: ~4s — extreme security, may impact UX
TipIncrease the cost factor as hardware improves. A good rule: each hash should take at least 250ms on your production hardware. Re-hash on login when you increase the cost.
Bcrypt hash format
$2b$12$N9qo8uLOickgx2ZMRZoMy.MrqK0aW8vB5qF8YdVxKQeDwWj5Z8aW
; $2b$ — version (2a, 2b, or 2y)
; $12$ — cost factor (2^12 = 4096 rounds)
; $N9qo8uLOickgx2ZMRZoMy. — 22-char base64 salt
; MrqK0aW8vB5qF8YdVxKQeDwWj5Z8aW — 31-char base64 hash
WarningBcrypt has a 72-byte password limit. Longer passwords are silently truncated. If you need to hash long passphrases, pre-hash with SHA-256 first, then bcrypt the result.
AES Encrypt / Decrypt
AES-GCM encryption with passphrase-derived keys
AES-GCM explained
AES (Advanced Encryption Standard) is a symmetric block cipher used worldwide. GCM (Galois/Counter Mode) is an authenticated encryption mode — it provides both confidentiality (nobody can read the data) and integrity (nobody can modify it without detection).
AES-GCM uses a 256-bit key and a 96-bit initialization vector (IV). The IV must be unique for each encryption with the same key — reusing an IV leaks the key. ShieldX generates a fresh random IV for every encryption.
Deriving a key from a passphrase
AES requires a 256-bit key, but humans use passphrases. PBKDF2 (Password-Based Key Derivation Function 2) bridges this gap by hashing the passphrase with a salt thousands of times, producing a key of the required length.
async function deriveKey(
passphrase: string,
salt: Uint8Array
): Promise<CryptoKey> {
const baseKey = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(passphrase),
'PBKDF2',
false,
['deriveKey']
);
return crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt,
iterations: 600_000, // OWASP recommendation for PBKDF2-SHA256
hash: 'SHA-256',
},
baseKey,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt']
);
}
TipOWASP recommends at least 600,000 iterations for PBKDF2 with SHA-256 as of 2023. This makes each derivation take ~500ms, which is acceptable for occasional encryption but too slow for high-throughput systems.
Encrypting and decrypting
async function encrypt(
plaintext: string,
key: CryptoKey
): Promise<{ iv: Uint8Array; ciphertext: ArrayBuffer }> {
const iv = crypto.getRandomValues(new Uint8Array(12));
const ciphertext = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
new TextEncoder().encode(plaintext)
);
return { iv, ciphertext };
}
async function decrypt(
ciphertext: ArrayBuffer,
key: CryptoKey,
iv: Uint8Array
): Promise<string> {
const plaintext = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv },
key,
ciphertext
);
return new TextDecoder().decode(plaintext);
}
WarningThe IV doesn't need to be secret, but it must be unique. Store the IV alongside the ciphertext — you'll need it for decryption. Never reuse an IV with the same key.
Secret / API Key Generator
Secure API keys and tokens using crypto.getRandomValues()
What makes a good API key?
A good API key has high entropy, is long enough to resist brute-force, and uses a charset that's URL-safe. A 256-bit key (32 bytes) in Base64 is 43 characters — sufficient for virtually any application.
- Hex: 64 chars for 256 bits — simple, double the length
- Base64: 43 chars for 256 bits — compact, may need URL-safe variant
- Base64URL: 43 chars for 256 bits — safe in URLs and JSON
- Custom alphabet: variable — useful for readable keys
Generating secure keys
// Generate a 256-bit key in hex
function generateHexKey(bytes: number = 32): string {
const arr = new Uint8Array(bytes);
crypto.getRandomValues(arr);
return [...arr].map((b) => b.toString(16).padStart(2, '0')).join('');
}
// Generate a 256-bit key in Base64URL
function generateBase64UrlKey(bytes: number = 32): string {
const arr = new Uint8Array(bytes);
crypto.getRandomValues(arr);
return btoa(String.fromCharCode(...arr))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
WarningNever use Math.random() or Date.now() to generate API keys. They are predictable and an attacker could enumerate valid keys. Always use crypto.getRandomValues().
API key best practices
- Prefix keys with a readable identifier (e.g., "sk_live_")
- Store only a hash of the key in your database
- Show the full key only once at generation time
- Support key rotation and revocation
- Rate-limit by key, not by IP
TipPrefixing keys (like "sk_live_" or "pk_test_") lets you identify the key type in logs and grep for accidental commits. GitHub and Stripe both use this pattern.
Privacy Policy Scanner
Detect tracking pixels and GDPR/CCPA disclosure gaps
What is a privacy policy scanner?
A privacy policy scanner analyzes a website's privacy policy and compares it against actual tracking behavior. It detects tracking pixels (Facebook Pixel, Google Analytics, TikTok Pixel), cookies, and fingerprinting scripts, then checks whether the privacy policy discloses them.
The gap between what a site tracks and what it discloses is a compliance risk under GDPR (EU), CCPA (California), and other privacy regulations.
Common tracking technologies
- Cookies: First-party and third-party, persistent and session
- Tracking pixels: 1×1 image requests that log visits
- Fingerprinting: Canvas, WebGL, and audio fingerprinting
- Beacons: navigator.sendBeacon() for analytics
- LocalStorage/IndexedDB: Client-side persistent storage
WarningUnder GDPR, tracking technologies require user consent before they are loaded. A privacy policy that mentions "cookies" but doesn't list specific trackers (Google Analytics, Facebook Pixel) may not be sufficient.
GDPR and CCPA requirements
GDPR requires: lawful basis for processing, data subject rights (access, deletion, portability), data breach notification, and privacy-by-design. CCPA requires: right to know, right to delete, right to opt-out of sale, and non-discrimination for exercising rights.
TipA privacy policy is just one piece of compliance. You also need a cookie consent mechanism, a data processing agreement with vendors, and a process for handling data subject requests.
Phishing URL Checker
Detect spoofing, punycode, and suspicious TLDs
Phishing URL techniques
Phishing URLs are designed to look like legitimate sites. Attackers use several techniques to deceive users and bypass security filters:
- Homograph attacks: paypa1.com (with a 1 instead of l)
- Punycode: xn--paypa-7ta.com displays as päypal.com
- Subdomain spoofing: login.paypal.com.evil.com
- URL shortening: bit.ly/secure-login
- Suspicious TLDs: .tk, .ml, .ga (free TLDs abused by phishers)
- Redirect chains: legitimate URL that redirects to a phishing page
Punycode homograph attacks
Internationalized Domain Names (IDNs) allow Unicode characters in domain names. Punycode encodes these as ASCII: "xn--" followed by an encoded string. An attacker can register "xn--paypa-7ta.com" which displays as "päypal.com" — visually identical to "paypal.com" at a glance.
WarningModern browsers display punycode for domains that mix scripts (e.g., Latin + Cyrillic), but same-script homographs are still displayed as Unicode. Always check the URL bar carefully before entering credentials.
How ShieldX detects phishing URLs
- Punycode detection: flag any domain using IDN encoding
- TLD reputation: check against known-abused TLDs
- Subdomain analysis: detect misleading subdomain patterns
- Redirect tracing: follow the URL to its final destination
- HTTPS check: flag HTTP login pages as suspicious
TipNo automated tool can catch 100% of phishing URLs. Always verify the domain in the address bar, use a password manager (which checks the domain before autofilling), and enable MFA.
Email Header Analyzer
Parse email headers, trace sender path, verify auth
What email headers reveal
Email headers contain the full journey of an email — every server it passed through, when it was sent, and what authentication checks it passed or failed. By analyzing headers, you can trace the true origin of an email and detect spoofing.
Key headers: Received (hop-by-hop trace), From/Reply-To (sender identity), SPF/DKIM/DMARC (authentication results), and Message-ID (unique identifier).
Tracing the sender path
Each Received header represents one server hop. Read them bottom-to-top (the oldest is at the bottom). The first Received header (bottommost) reveals the true originating IP — all subsequent hops are mail servers relaying the message.
TipIf the originating IP is in a residential IP range or a known VPN/proxy, the email was likely sent from a compromised account or a botnet. Legitimate business email originates from the company's mail server IP range.
Authentication result analysis
Modern email includes Authentication-Results headers showing SPF, DKIM, and DMARC outcomes. ShieldX parses these and flags any failures:
- SPF=pass: Sending IP is authorized by the domain's SPF record
- DKIM=pass: Email signature is valid and unmodified
- DMARC=pass: At least one of SPF/DKIM aligned with the From domain
- Any fail: The email may be spoofed — investigate further
WarningA spoofed email can pass SPF if the attacker uses a domain they control in the envelope sender (Return-Path) while forging the From header. DMARC alignment prevents this by requiring the From domain to match SPF/DKIM domains.
QR Code Security Scanner
Decode QR images and check embedded URLs for phishing
The quishing threat
Quishing (QR code phishing) attacks have surged 587% since 2022. Attackers embed malicious URLs in QR codes — in emails, printed posters, parking meters, and restaurant menus. Users scan the code and are taken to a phishing site without seeing the URL first.
QR codes are dangerous because they bypass the visual URL inspection that protects users from traditional phishing. You can't see where a QR code leads until you've already scanned it.
How ShieldX scans QR codes
- Upload or paste a QR code image
- Decode the QR code locally in your browser
- Extract the embedded URL
- Run phishing detection (punycode, suspicious TLDs, redirect tracing)
- Report the destination and any risks found
TipBefore scanning a QR code in public, consider who placed it there and whether it's been tampered with. Stickers over legitimate QR codes are a common attack vector.
CSP Evaluator
Parse CSP directives and detect unsafe patterns
Content-Security-Policy fundamentals
Content-Security-Policy (CSP) is the most powerful client-side security header. It restricts which resources (scripts, styles, images, frames, etc.) can load and execute on your page. A well-configured CSP can prevent virtually all XSS attacks.
CSP works by specifying allowlists for each resource type. If a resource isn't in the allowlist, the browser blocks it. The challenge is building a CSP that's strict enough to be secure but permissive enough to not break your site.
Key CSP directives
- default-src: Fallback for all resource types
- script-src: JavaScript sources (most critical)
- style-src: CSS sources
- img-src: Image sources
- connect-src: XHR, fetch, WebSocket origins
- frame-src: iframe sources
- font-src: Font sources
- object-src: Plugin sources (Flash, Java — should be 'none')
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-r4nd0mN0nc3';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
connect-src 'self' https://api.example.com;
object-src 'none';
base-uri 'self';
frame-ancestors 'none';
Detecting unsafe CSP patterns
ShieldX flags the following CSP anti-patterns:
- unsafe-inline: Allows inline scripts/styles — defeats XSS protection
- unsafe-eval: Allows eval() — code injection risk
- Wildcard domains (*.com): Too broad, allows any .com site
- Missing object-src: Defaults to allowing plugins
- Missing base-uri: Allows <base> tag injection
- data: in script-src: Allows script injection via data URLs
TipReplace unsafe-inline with nonces or hashes. A nonce is a random value generated per request: script-src 'self' 'nonce-abc123'. Only scripts with the matching nonce attribute execute.
What is password entropy?
The mathematical foundation of password strength
Entropy is the measure of unpredictability in a password. It is expressed in bits and calculated as log2(charsetSize^length). A password drawn from 62 possible characters (a–z, A–Z, 0–9) at a length of 16 has log2(62^16) ≈ 95.3 bits of entropy. The higher the entropy, the more guesses an attacker needs to crack it.
The critical insight: entropy grows exponentially with length but only logarithmically with charset size. Doubling your charset adds 1 bit per character. Doubling your length doubles your total entropy. This is why a 20-character lowercase password (93 bits) is stronger than an 8-character mixed-character password (47 bits).
// Entropy calculation — the honest way
function entropyBits(charsetSize: number, length: number): number {
return Math.log2(charsetSize) * length;
}
// 8 chars, 62 charset (a-z A-Z 0-9)
entropyBits(62, 8); // 47.6 bits → ~7.6 quadrillion guesses
// 20 chars, 26 charset (a-z only)
entropyBits(26, 20); // 94.0 bits → ~1.6 × 10^28 guesses
// 16 chars, 94 charset (full keyboard)
entropyBits(94, 16); // 105.0 bits → ~3.3 × 10^31 guesses
TipAim for at least 80 bits of entropy for everyday accounts and 128 bits for critical credentials like password manager master passwords or encryption keys.
Estimating crack time honestly
Why most password meters lie — and how to fix them
Most online password meters show a green bar for "Password1!" because it has uppercase, lowercase, a number, and a symbol. But its entropy is only ~33 bits. At a conservative hash rate of 10^10 guesses per second (offline attack against a fast hash), that is crackable in under a minute.
Honest crack-time estimation requires three inputs: the actual entropy (not a heuristic score), the attacker hash rate (which varies by hash function), and the attack model (online vs offline). ShieldX computes all three and presents the result in human-readable units.
function crackTime(entropyBits: number, guessesPerSec: number): string {
const totalGuesses = Math.pow(2, entropyBits) / 2; // average case
const seconds = totalGuesses / guessesPerSec;
if (seconds < 1) return 'instant';
if (seconds < 60) return `${Math.round(seconds)} seconds`;
if (seconds < 3600) return `${Math.round(seconds / 60)} minutes`;
if (seconds < 86400) return `${Math.round(seconds / 3600)} hours`;
if (seconds < 31536000) return `${Math.round(seconds / 86400)} days`;
const years = seconds / 31536000;
if (years < 1e6) return `${Math.round(years).toLocaleString()} years`;
return `${years.toExponential(1)} years`;
}
// Example: 95 bits of entropy, offline attack at 10^10 guesses/sec
crackTime(95, 1e10);
// → "2,070,168 years"
WarningCrack-time estimates assume random generation. Human-chosen passwords with patterns (keyboard walks, substitutions, word combinations) have far less entropy than their character set suggests. Always generate passwords with a CSPRNG.
The Web Crypto API in practice
Cryptographic randomness directly from the browser
The Web Crypto API exposes crypto.getRandomValues(), which draws from the operating system CSPRNG (the same source used for TLS handshakes). This is fundamentally different from Math.random(), which uses a PRNG seeded with a predictable value and is unsuitable for any security purpose.
Every ShieldX tool that needs randomness — password generation, UUID creation, random number generation, dice rolls — uses getRandomValues() exclusively. The output is unbiased and indistinguishable from true randomness for any practical purpose.
// Secure: Web Crypto API
function secureRandomInt(max: number): number {
const array = new Uint32Array(1);
crypto.getRandomValues(array);
// Rejection sampling eliminates modulo bias
const maxUint32 = 0xFFFFFFFF;
const limit = maxUint32 - (maxUint32 % max);
if (array[0] >= limit) return secureRandomInt(max);
return array[0] % max;
}
// Insecure: Math.random() — NEVER use for security
// Math.random() uses a deterministic PRNG (xorshift128+)
// Its output is predictable if the internal state is known.
TipYou can verify this yourself. Open ShieldX in your browser, open DevTools → Network tab, generate a password, and watch the network panel stay completely empty.
Password best practices for 2025
What NIST, EFF, and security researchers actually recommend
NIST SP 800-63B (2023 revision) overturned decades of bad advice. The standard now explicitly recommends against forced password complexity rules, mandatory periodic resets, and knowledge-based authentication questions. Instead, it prioritizes length, randomness, and breach checking.
Do:
- Use passwords of at least 12 characters, preferably 16+ generated randomly
- Use a password manager to store unique passwords for every account
- Check passwords against breach databases before use (k-anonymity model)
- Enable multi-factor authentication wherever available
- Use passkeys (WebAuthn) when supported — they eliminate passwords entirely
Don't:
- Force users to include specific character types (uppercase, symbols, numbers)
- Require periodic password resets without evidence of compromise
- Use security questions with guessable answers (mother's maiden name, etc.)
- Truncate passwords or limit them to artificially short lengths
- Store passwords in plaintext, reversible encryption, or fast hashes (MD5, SHA-1)
TipThe EFF Diceware word list is an excellent resource for generating memorable high-entropy passphrases. Six random words from the 7,776-word list provide ~77 bits of entropy.
Browser-based security architecture
Why most security tools do not need a server
The traditional model for online security tools involves a backend server that processes user input and returns results. This creates a trust problem: the user must believe that the server does not log, store, or analyze their data. ShieldX eliminates this trust requirement entirely for most tools.
Password generation, strength checking, hashing, UUID generation, random number generation, and Base64 encoding all run entirely in the browser using the Web Crypto API. No data ever leaves the user's device. The only tools that require a server are those that need to contact a third party (SSL checks, header scans, DNS lookups), and even those use stateless Cloudflare Workers that process only the domain you typed and retain nothing.
// Architecture comparison
// Traditional: user input → server → database → response
// Risk: server logs, database leaks, subpoena, insider threat
// ShieldX: user input → browser → Web Crypto API → response
// Risk: none (no server contact, no storage, no logging)
// Hybrid (SSL/headers/DNS): user input → browser → stateless worker → response
// Risk: minimal (worker processes domain only, retains nothing)
This architecture is verifiable. The source code is open, so you can audit every line before trusting it. Or simply open DevTools and confirm that the Network tab stays empty when you generate a password.
Breach checking without exposing your password
The k-anonymity model explained
Checking whether a password has appeared in a known data breach seems to require sending the password to a server. The k-anonymity model, pioneered by the Have I Been Pwned API, solves this problem elegantly: only the first 5 characters of the password's SHA-1 hash are sent.
The server returns all breach entries whose hashes start with those 5 characters — potentially thousands of entries. The client then checks whether the full hash matches any of them locally. The server never sees enough information to identify your specific password.
async function checkBreach(password: string): Promise<number> {
// 1. Hash the password locally with SHA-1
const data = new TextEncoder().encode(password);
const hashBuffer = await crypto.subtle.digest('SHA-1', data);
const fullHash = Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('')
.toUpperCase();
// 2. Send only the first 5 characters to the API
const prefix = fullHash.slice(0, 5);
const response = await fetch(
`https://api.pwnedpasswords.com/range/${prefix}`
);
const text = await response.text();
// 3. Check the suffix locally — the server never sees it
const suffix = fullHash.slice(5);
const match = text
.split('\n')
.find(line => line.split(':')[0] === suffix);
return match ? parseInt(match.split(':')[1]) : 0;
}
TipWith 5 hex characters, the prefix space is 16^5 = 1,048,576 buckets. Each bucket contains thousands of hashes, so the server cannot determine which specific password you are checking.
Passphrases and the EFF Diceware word list
Why four random words beat your clever password
Passphrases are the practical alternative to random character passwords. Instead of memorizing "K7$mP9!nQw2#vR4x", you memorize "correct horse battery staple" — four common words that are easier to remember, easier to type, and often stronger. The EFF Diceware word list is the gold standard: 7,776 words curated for memorability, unambiguity, and minimal profanity.
Each word selected from the 7,776-word list contributes log2(7776) ≈ 12.9 bits of entropy. Four words give ~52 bits, five give ~65 bits, and six give ~77 bits — comparable to a 12-character random password but far more memorable. The key requirement is that word selection must use a CSPRNG, not human choice.
// EFF Diceware passphrase generation
const EFF_WORDS = 7776; // word list length
function passphraseEntropy(wordCount: number): number {
return Math.log2(EFF_WORDS) * wordCount;
}
passphraseEntropy(4); // 51.7 bits — good for everyday accounts
passphraseEntropy(5); // 64.6 bits — strong
passphraseEntropy(6); // 77.5 bits — excellent, NIST-aligned
passphraseEntropy(7); // 90.5 bits — critical credentials
// Generation with rejection sampling (no modulo bias)
function pickWord(words: string[]): string {
const max = words.length;
const array = new Uint32Array(1);
crypto.getRandomValues(array);
const limit = 0xFFFFFFFF - (0xFFFFFFFF % max);
if (array[0] >= limit) return pickWord(words);
return words[array[0] % max];
}
Why the EFF list over the original Diceware list
- No profanity or offensive words — safe for all contexts and age groups
- Minimal homophones and ambiguous spellings — reduces transcription errors
- Words are 3–9 characters — short enough to type, long enough to be distinct
- No words containing apostrophes, hyphens, or spaces — clean concatenation
- Curated by the Electronic Frontier Foundation with security community input
TipThe ShieldX Passphrase Generator uses the EFF word list with CSPRNG selection and rejection sampling. Choose 4–10 words, add optional separators, and get real entropy calculations — not guesswork.
SSL/TLS certificate chains and grading
What a certificate actually proves — and what it does not
An SSL/TLS certificate is a digital document that binds a domain name to a public key. The certificate is signed by a Certificate Authority (CA) that the browser trusts, creating a chain of trust from a root CA through intermediate CAs to the server certificate. When you connect to a website, the server presents its certificate chain, and the browser verifies each signature up to a trusted root.
Certificate inspection reveals far more than just "is it valid?". The protocol version (TLS 1.2 vs 1.3), cipher suite strength (ECDHE + AES-GCM vs RSA + CBC), key size (256-bit vs 128-bit), chain completeness (missing intermediates cause errors on some clients), and expiry date all affect the security posture. A certificate can be valid but weak.
// Simplified certificate chain validation logic
interface CertInfo {
subject: string;
issuer: string;
validFrom: Date;
validTo: Date;
keyAlgorithm: string;
keySize: number;
protocolVersion: string;
cipherSuite: string;
}
function gradeCert(cert: CertInfo): string {
let score = 100;
// Protocol version
if (cert.protocolVersion === 'TLS 1.3') score -= 0;
else if (cert.protocolVersion === 'TLS 1.2') score -= 5;
else score -= 30; // TLS 1.0/1.1 are deprecated
// Key size
if (cert.keySize < 2048) score -= 20;
else if (cert.keySize < 3072) score -= 5;
// Expiry within 30 days
const daysLeft = (cert.validTo.getTime() - Date.now()) / 86400000;
if (daysLeft < 0) return 'F — Expired';
if (daysLeft < 7) score -= 15;
else if (daysLeft < 30) score -= 5;
// Cipher suite
if (!cert.cipherSuite.includes('GCM') && !cert.cipherSuite.includes('Poly1305'))
score -= 10; // No authenticated encryption
if (score >= 95) return 'A+';
if (score >= 90) return 'A';
if (score >= 80) return 'B';
if (score >= 70) return 'C';
if (score >= 60) return 'D';
return 'F';
}
WarningA valid certificate only proves that a CA verified domain control at issuance time. It does not prove the site is legitimate, safe, or trustworthy. Phishing sites routinely obtain valid certificates through automated CAs like Let's Encrypt.
TipThe ShieldX SSL Certificate Checker inspects the full chain, grades A+ to F, checks protocol versions, cipher strength, and expiry — with bulk scanning for up to 50 domains.
Security headers: CSP, HSTS, and friends
The HTTP response headers every site should set
HTTP security headers are the first line of defense against client-side attacks. They instruct the browser to enforce policies that prevent cross-site scripting, clickjacking, MIME-type sniffing, and protocol downgrade attacks. A site without security headers is vulnerable even with a valid SSL certificate.
The essential security headers
- Content-Security-Policy (CSP) — restricts which sources can load scripts, styles, images, and other resources. The most powerful XSS mitigation available
- Strict-Transport-Security (HSTS) — forces HTTPS for all future visits, preventing protocol downgrade and SSL stripping attacks
- X-Content-Type-Options: nosniff — prevents the browser from interpreting files as a different MIME type than declared
- X-Frame-Options: DENY or CSP frame-ancestors — prevents the page from being embedded in an iframe (clickjacking defense)
- Referrer-Policy — controls how much referrer information is sent with cross-origin requests
- Permissions-Policy — disables unused browser APIs like camera, microphone, and geolocation
# Nginx — add to server block
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self';" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), interest-cohort=()" always;
# Apache — add to .htaccess or VirtualHost
<IfModule mod_headers.c>
Header always set Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self';"
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "DENY"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Permissions-Policy "camera=(), microphone=(), geolocation=(), interest-cohort=()"
</IfModule>
CSP is the most complex and most powerful header. A well-crafted CSP blocks inline scripts, restricts resource loading to trusted origins, and reports violations. The key principle is default-src 'self' — deny everything by default, then allow only what is needed. Avoid 'unsafe-inline' and 'unsafe-eval' in script-src; use nonces or hashes instead.
WarningHSTS with preload is irreversible. Once your domain is on the HSTS preload list, you cannot remove it for at least a year. Test thoroughly before submitting at hstspreload.org.
TipThe ShieldX Security Headers Scanner audits all headers, scores 0–100, and provides copy-paste fix recommendations. The CSP Evaluator separately parses and analyzes CSP directives for unsafe-inline, unsafe-eval, and missing directives.
DNS over HTTPS and DNSSEC validation
Why plaintext DNS is a privacy and security problem
Traditional DNS queries are sent in plaintext over UDP port 53. Anyone on the network path — your ISP, a coffee shop Wi-Fi operator, or a nation-state — can see every domain you look up and modify responses in transit. DNS-over-HTTPS (DoH) encrypts queries inside HTTPS connections, and DNSSEC cryptographically signs records so forged responses are detectable.
DoH sends DNS queries to a resolver over an HTTPS connection, typically using JSON or binary wire format. The query and response are encrypted, authenticated, and indistinguishable from normal HTTPS traffic. Popular public resolvers include Cloudflare (1.1.1.1), Google (8.8.8.8), and Quad9 (9.9.9.9).
// DNS-over-HTTPS query using Cloudflare resolver
async function dohQuery(domain: string, type: string): Promise<any> {
const url = `https://cloudflare-dns.com/dns-query?name=${encodeURIComponent(domain)}&type=${type}`;
const response = await fetch(url, {
headers: { 'Accept': 'application/dns-json' },
});
return response.json();
}
// Example: query A records for example.com
const result = await dohQuery('example.com', 'A');
// { Status: 0, Answer: [{ name: 'example.com', type: 1, TTL: 300, data: '93.184.216.34' }] }
// DNSSEC validation: check AD (Authenticated Data) flag
// Status 0 = NOERROR, AD bit set means DNSSEC validated
DNSSEC: cryptographic signatures on DNS records
DNSSEC adds digital signatures to DNS records using public-key cryptography. Each zone publishes a public key (DNSKEY record) and signs its records (RRSIG records). Resolvers validate the chain of trust from the root zone down to the target domain. If validation fails, the resolver returns a SERVFAIL response, protecting the client from forged records.
- A records — IPv4 addresses, the most common query type
- AAAA records — IPv6 addresses
- CNAME records — canonical name aliases (one domain points to another)
- MX records — mail exchange servers for the domain
- TXT records — arbitrary text, used for SPF, DKIM, domain verification
- NS records — authoritative name servers for the domain
- CAA records — which CAs are allowed to issue certificates
- SOA records — start of authority, zone metadata
TipThe ShieldX DNS Lookup queries every record type over DoH with DNSSEC validation and supports three resolvers. The CAA Record Checker specifically parses CAA records to verify which CAs are authorized.
Hashing algorithms: MD5 to SHA-512 and beyond
One-way functions, collision resistance, and when to use each
A cryptographic hash function takes input of arbitrary size and produces a fixed-size output (digest) that is deterministic, fast to compute, infeasible to reverse, and collision-resistant. The Web Crypto API supports SHA-1, SHA-256, SHA-384, and SHA-512 natively through crypto.subtle.digest().
MD5 (128-bit) and SHA-1 (160-bit) are broken for cryptographic purposes — practical collision attacks exist. MD5 should only be used for non-security checksums. SHA-1 should only be used for legacy compatibility (like breach checking with HIBP). For any new security application, use SHA-256 or stronger.
// Hashing with the Web Crypto API
async function hash(data: string, algorithm: string): Promise<string> {
const encoder = new TextEncoder();
const dataBuffer = encoder.encode(data);
const hashBuffer = await crypto.subtle.digest(algorithm, dataBuffer);
return Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
await hash('hello', 'SHA-256');
// "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
await hash('hello', 'SHA-512');
// "9b71d224bd62f3785d96d46ad3fb3da5d4...512 bits total"
// File hashing — read as ArrayBuffer, then digest
async function hashFile(file: File, algorithm: string): Promise<string> {
const buffer = await file.arrayBuffer();
const hashBuffer = await crypto.subtle.digest(algorithm, buffer);
return Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
Hash length and format reference
| Algorithm | Output length | Hex length | Security |
|---|---|---|---|
| MD5 | 128 bits | 32 chars | Broken — collisions found, use only for checksums |
| SHA-1 | 160 bits | 40 chars | Broken — use only for legacy/HIBP |
| SHA-256 | 256 bits | 64 chars | Secure — standard choice |
| SHA-384 | 384 bits | 96 chars | Secure — high assurance |
| SHA-512 | 512 bits | 128 chars | Secure — high assurance |
| bcrypt | 184 bits | 60 chars | Secure — password storage, includes salt + cost |
WarningNever use plain SHA-256 for password storage. Passwords need slow, salted hashes like bcrypt, scrypt, or Argon2id. SHA-256 is a fast hash — an attacker with a GPU can try billions of guesses per second against a SHA-256 hash.
TipThe ShieldX Hash Generator supports MD5, SHA-1, SHA-256, SHA-384, and SHA-512 for text and files. The Hash Identifier detects 60+ hash types by length and format pattern. The Bcrypt Generator handles password-specific hashing with adjustable cost factors.
AES-GCM encryption in the browser
Authenticated encryption with the Web Crypto API
AES-GCM (Galois/Counter Mode) is the recommended authenticated encryption mode for the web. It provides both confidentiality (nobody can read the data without the key) and integrity (nobody can tamper with the ciphertext without detection). The Web Crypto API supports it natively through crypto.subtle.encrypt() and crypto.subtle.decrypt().
For password-based encryption, the key must be derived from the passphrase using a key derivation function like PBKDF2. This stretches a low-entropy password into a high-entropy 256-bit key using many iterations of a hash function. The salt and IV (initialization vector) are not secret — they are stored alongside the ciphertext and needed for decryption.
// AES-GCM encryption with PBKDF2 key derivation
async function deriveKey(password: string, salt: Uint8Array): Promise<CryptoKey> {
const material = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(password),
'PBKDF2',
false,
['deriveKey'],
);
return crypto.subtle.deriveKey(
{ name: 'PBKDF2', hash: 'SHA-256', salt, iterations: 250000 },
material,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt'],
);
}
async function encrypt(password: string, plaintext: string) {
const salt = crypto.getRandomValues(new Uint8Array(16));
const iv = crypto.getRandomValues(new Uint8Array(12));
const key = await deriveKey(password, salt);
const ciphertext = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
new TextEncoder().encode(plaintext),
);
return { salt, iv, ciphertext };
}
async function decrypt(password: string, data: { salt: Uint8Array; iv: Uint8Array; ciphertext: ArrayBuffer }) {
const key = await deriveKey(password, data.salt);
const plaintext = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: data.iv },
key,
data.ciphertext,
);
return new TextDecoder().decode(plaintext);
}
AES-GCM provides built-in authentication — if the ciphertext is modified, decryption throws an OperationError. This means a wrong password does not produce garbage output; it produces an error. This is a critical security property that CBC and CTR modes lack by default.
- IV must be unique per encryption with the same key — 12 bytes is the recommended length for GCM
- IV is not secret — store it alongside the ciphertext
- Salt must be unique per encryption — 16 bytes from crypto.getRandomValues()
- Salt is not secret — store it alongside the ciphertext
- Use at least 250,000 PBKDF2 iterations for password-based keys (adjust based on hardware)
- Never reuse the same IV with the same key — this breaks GCM security entirely
TipThe ShieldX AES Encrypt/Decrypt tool uses AES-GCM 256 with PBKDF2 key derivation — all in your browser. Your passphrase and plaintext never leave your device.
HMAC and message authentication
Proving a message came from someone who has the secret
HMAC (Hash-based Message Authentication Code) combines a cryptographic hash function with a secret key to produce a signature that proves both data integrity and authenticity. Unlike a plain hash, an attacker cannot forge an HMAC without knowing the secret key. The Web Crypto API supports HMAC with SHA-256, SHA-384, and SHA-512 through crypto.subtle.sign() and crypto.subtle.verify().
HMAC is the backbone of API authentication. Services like Stripe, GitHub webhooks, and AWS S3 use HMAC to sign requests: the client computes HMAC-SHA256(request_body, secret_key) and sends the signature in a header. The server recomputes the HMAC with its copy of the secret and compares. If they match, the request is authentic and unmodified.
// HMAC signing with the Web Crypto API
async function hmacSign(message: string, secret: string): Promise<string> {
const key = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign', 'verify'],
);
const signature = await crypto.subtle.sign(
'HMAC',
key,
new TextEncoder().encode(message),
);
return Array.from(new Uint8Array(signature))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
async function hmacVerify(message: string, signature: string, secret: string): Promise<boolean> {
const key = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign', 'verify'],
);
const sigBytes = new Uint8Array(
signature.match(/.{2}/g)!.map(b => parseInt(b, 16)),
);
return crypto.subtle.verify(
'HMAC',
key,
sigBytes,
new TextEncoder().encode(message),
);
}
Common HMAC use cases
- Webhook signature verification — Stripe, GitHub, Slack send HMAC in headers
- API request signing — AWS Signature Version 4 uses HMAC-SHA256
- Session tokens — stateless auth with HMAC-signed payloads
- Request replay prevention — sign timestamp + nonce to prevent replay attacks
- Cookie integrity — sign cookie values to detect tampering
WarningAlways use constant-time comparison when verifying HMAC signatures. JavaScript's === operator short-circuits on the first differing byte, enabling timing attacks. The Web Crypto API's verify() method uses constant-time comparison internally — always prefer it over manual comparison.
TipThe ShieldX HMAC Generator creates HMAC-SHA256/384/512 signatures with hex and Base64 output formats — entirely client-side, so your secret key never leaves your browser.
JWT structure, attacks, and safe decoding
Three base64 strings that carry your identity — and their risks
A JSON Web Token (JWT) is three base64url-encoded JSON objects separated by dots: header.payload.signature. The header declares the signing algorithm, the payload carries claims (user ID, roles, expiry), and the signature proves integrity. JWTs are stateless — the server does not need to look up a session, it just verifies the signature.
// JWT decoding — 100% client-side, no verification needed to read
function decodeJWT(token: string): { header: any; payload: any } {
const [headerB64, payloadB64] = token.split('.');
// base64url → base64 → JSON
const decode = (b64url: string) => {
const b64 = b64url.replace(/-/g, '+').replace(/_/g, '/');
const json = atob(b64);
return JSON.parse(json);
};
return {
header: decode(headerB64),
payload: decode(payloadB64),
};
}
// Example token
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
const { header, payload } = decodeJWT(token);
// header: { alg: "HS256", typ: "JWT" }
// payload: { sub: "1234567890", name: "John Doe", iat: 1516239022 }
The alg:none attack
The most notorious JWT vulnerability is the alg:none attack. The JWT specification defines "none" as a valid algorithm for unsigned tokens. If a server trusts the algorithm declared in the token header instead of pinning its own expected algorithm, an attacker can change the header to {"alg":"none"}, modify the payload to grant admin privileges, remove the signature, and the server accepts it. CVE-2015-9235 was the canonical disclosure; variants still appear in production today.
The fix is simple: always specify an allowlist of algorithms on the server side. Never let the token's own alg header determine which verification algorithm is used. Reject "none" explicitly, and never mix symmetric and asymmetric algorithms in the same verifier (this prevents algorithm confusion attacks where an attacker switches RS256 to HS256 and signs with the public key).
Common JWT claims to check
- exp (expires at) — reject expired tokens; compare against current time
- iat (issued at) — when the token was created; detect future-dated tokens
- nbf (not before) — token is not valid before this timestamp
- iss (issuer) — who issued the token; verify it matches your auth server
- aud (audience) — who the token is for; verify it matches your application
- sub (subject) — the user/entity identifier
- scope — what permissions the token grants
WarningDecoding a JWT is not the same as verifying it. Anyone can base64-decode a JWT and read the payload — it is not encrypted. The signature only proves integrity, not confidentiality. Never put sensitive data in a JWT payload.
TipThe ShieldX JWT Decoder decodes header and payload, flags alg:none attacks, checks token expiry, and validates the iat/nbf/exp claims — all client-side.
Phishing detection: punycode, suspicious TLDs, and redirects
How to spot a fake URL before you click
Phishing is the most common initial attack vector, and it almost always starts with a URL. The URL looks legitimate at first glance — the domain is close to the real one, the path mimics a login page, the SSL certificate is valid. But subtle tells give it away: punycode homograph attacks, suspicious TLDs, redirect chains, and IDN spoofing.
Punycode and homograph attacks
Punycode is an encoding that allows internationalized domain names (IDNs) to use Unicode characters. An attacker registers a domain using Cyrillic characters that look identical to Latin ones — for example, "аpple.com" where the first "а" is Cyrillic U+0430, not Latin U+0061. The browser displays it as "аpple.com" but the actual domain is "xn--80ak6aa92e.com". This is a homograph attack.
// Punycode detection
function detectPunycode(url: string): boolean {
try {
const hostname = new URL(url).hostname;
// Punycode labels start with "xn--"
return hostname.split('.').some(label => label.startsWith('xn--'));
} catch {
return false;
}
}
// Suspicious TLD check
const SUSPICIOUS_TLDS = [
'.tk', '.ml', '.ga', '.cf', '.gq', // free TLDs, high abuse rate
'.top', '.xyz', '.click', '.link', // cheap registration
'.country', '.stream', '.download', // frequently used in phishing
];
function hasSuspiciousTLD(url: string): boolean {
const hostname = new URL(url).hostname.toLowerCase();
return SUSPICIOUS_TLDS.some(tld => hostname.endsWith(tld));
}
// IP address hostname (common in phishing)
function isIPHostname(url: string): boolean {
const hostname = new URL(url).hostname;
return /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname);
}
Other URL red flags
- Subdomain spoofing — "login.paypal.com.secure-check.example.com" uses "paypal.com" as a subdomain bait
- Excessive subdomains — "verify.account.update.security.example.com" tries to look official
- URL shortener chains — shorteners hide the final destination; follow redirects to check
- Embedded credentials — "https://google.com@evil.com" uses "google.com" as a username, not the host
- Data URIs — "data:text/html,<script>..." can render fake login pages without a domain
- Misspelled domains — "g00gle.com", "arnazon.com", "paypa1.com" rely on visual similarity
WarningA valid SSL certificate does not mean a site is safe. Let's Encrypt and other automated CAs issue certificates in seconds with only domain control verification. Phishing sites routinely have valid HTTPS. The padlock icon is not a trust indicator — it only means the connection is encrypted.
TipThe ShieldX Phishing URL Checker detects punycode homograph attacks, flags suspicious TLDs, traces redirect chains, and identifies subdomain spoofing. The QR Code Security Scanner applies the same checks to URLs embedded in QR codes.
Email authentication: SPF, DKIM, and DMARC
Three DNS records that prevent email spoofing
Email spoofing is trivial by default — the SMTP protocol does not verify the sender address. Anyone can send an email that appears to come from any address. Three DNS-based standards fix this: SPF authorizes sending servers, DKIM signs messages cryptographically, and DMARC ties them together with a policy for failures.
SPF (Sender Policy Framework)
SPF is a TXT record in DNS that lists the IP addresses and servers authorized to send email for a domain. When a receiving mail server gets a message, it checks the sender's SPF record. If the sending IP is not listed, the message is suspicious. SPF is simple but has limitations: it breaks on forwarded email and does not sign the message content.
# SPF record — authorize specific servers
example.com. TXT "v=spf1 ip4:192.0.2.0/24 include:_spf.google.com ~all"
# Breakdown:
# v=spf1 — SPF version
# ip4:192.0.2.0/24 — authorize this IP range
# include:_spf.google.com — also include Google's SPF records
# ~all — softfail for everything else (mark as spam)
# -all — hardfail (reject)
# ?all — neutral (no policy)
DKIM (DomainKeys Identified Mail)
DKIM adds a digital signature to each outgoing email. The signing server uses a private key to sign selected headers and the message body. The public key is published in a DNS TXT record. The receiving server retrieves the public key and verifies the signature. DKIM survives forwarding because the signature is in the email headers, not the envelope.
DMARC (Domain-based Message Authentication)
DMARC is the policy layer. It tells receiving servers what to do when SPF or DKIM fail: do nothing (p=none), send to spam (p=quarantine), or reject (p=reject). DMARC also adds reporting — aggregate reports (RUA) show which senders are passing and failing, and forensic reports (RUF) send samples of failed messages.
# DMARC record — enforce policy
_dmarc.example.com. TXT "v=DMARC1; p=reject; rua=mailto:dmarc@example.com; ruf=mailto:dmarc@example.com; fo=1; adkim=s; aspf=s"
# Breakdown:
# v=DMARC1 — DMARC version
# p=reject — reject messages that fail authentication
# rua=mailto: — where to send aggregate reports
# ruf=mailto: — where to send forensic reports
# fo=1 — send forensic report on any authentication failure
# adkim=s — strict DKIM alignment (domain must match exactly)
# aspf=s — strict SPF alignment
WarningSPF has a 10-DNS-lookup limit. If your SPF record includes more than 10 domains via include mechanisms, receivers will stop evaluating and treat the message as unauthorized. This is called "SPF permerror." Use SPF flattening services or reduce includes.
TipThe ShieldX DMARC/SPF/DKIM Checker queries all three records, counts SPF lookups, and flags misconfigurations. The Email Header Analyzer parses raw email headers and verifies SPF, DKIM, and DMARC authentication results hop by hop.
Bcrypt and password hashing
Why fast hashes are dangerous for passwords
Password hashing is fundamentally different from general-purpose hashing. SHA-256 is designed to be fast — a GPU can compute billions of SHA-256 hashes per second. For password storage, fast is bad: an attacker who steals a database of SHA-256 hashes can try billions of guesses per second. Bcrypt is deliberately slow and adaptive — it can be made slower as hardware improves.
Bcrypt has two key features that make it suitable for password storage: a salt (random data mixed into the hash, preventing rainbow table attacks) and a cost factor (determines how many rounds of the Blowfish cipher to run, directly controlling computation time). The cost factor is exponential — increasing it by 1 doubles the computation time.
// Bcrypt hash format: $2b$cost$salt+hash
// $2b$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy
// ^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// algo cost 22-char salt + 31-char hash (base64)
// Cost factor comparison (approximate, modern GPU):
// Cost 10: ~60ms per hash → ~17,000 hashes/sec
// Cost 12: ~240ms per hash → ~4,200 hashes/sec
// Cost 14: ~960ms per hash → ~1,000 hashes/sec
// Cost 16: ~3.8s per hash → ~0.26 hashes/sec
// Choosing the cost factor:
// Target: ~250ms per hash on your production hardware
// Start at 10, increase by 1 until you hit the target
// Re-hash on login: when a user logs in, re-hash with current cost
// if their stored hash has a lower cost factor
Bcrypt vs other password hashing algorithms
| Algorithm | Memory | GPU resistance | Recommendation |
|---|---|---|---|
| bcrypt | 4 KB | Moderate | Good — widely supported, well-tested |
| scrypt | tunable MB | High | Better — memory-hard, GPU expensive |
| Argon2id | tunable MB | Highest | Best — PHC winner, recommended for new systems |
| PBKDF2 | Minimal | Low | Acceptable — only if bcrypt/Argon2 unavailable |
| SHA-256 | Minimal | None | Never — too fast, not a password hash |
WarningNever roll your own password hashing implementation. Use a well-tested library. For browser-based hashing, bcrypt can be slow (blocking the main thread) — consider using a Web Worker or WASM implementation to avoid UI freezes.
TipThe ShieldX Bcrypt Generator creates and compares bcrypt hashes with adjustable cost factors. Use it to test password storage implementations or verify hash formats.
CVSS v3.1 vulnerability scoring
The standard framework for rating severity
The Common Vulnerability Scoring System (CVSS) v3.1 is the industry standard for rating software vulnerability severity. It produces a score from 0.0 to 10.0 based on eight Base Metrics that capture the intrinsic characteristics of a vulnerability — constant across time and environments. The score is accompanied by a vector string that encodes all metric values.
The Base Score is computed from two sub-scores: Exploitability (how easy it is to attack) and Impact (how bad it is if exploited). Exploitability considers Attack Vector, Attack Complexity, Privileges Required, and User Interaction. Impact considers Confidentiality, Integrity, and Availability — plus Scope, which captures whether the vulnerability crosses trust boundaries.
// CVSS v3.1 Base Score calculation (simplified)
const METRICS = {
// Attack Vector: how the vulnerability is accessed
AV: { N: 0.85, A: 0.62, L: 0.55, P: 0.2 }, // Network/Adjacent/Local/Physical
// Attack Complexity: conditions beyond attacker's control
AC: { L: 0.77, H: 0.44 }, // Low/High
// Privileges Required: what the attacker needs before
PR: { N: 0.85, L: 0.62, H: 0.27 }, // None/Low/High
// User Interaction: does a user need to do something?
UI: { N: 0.85, R: 0.62 }, // None/Required
// Impact: Confidentiality, Integrity, Availability
C: { H: 0.56, L: 0.22, N: 0 }, // High/Low/None
I: { H: 0.56, L: 0.22, N: 0 },
A: { H: 0.56, L: 0.22, N: 0 },
};
function cvssBaseScore(av, ac, pr, ui, scope, c, i, a): number {
const exploitability = 8.22 * METRICS.AV[av] * METRICS.AC[ac]
* METRICS.PR[pr] * METRICS.UI[ui];
const iscBase = 1 - (
(1 - METRICS.C[c]) * (1 - METRICS.I[i]) * (1 - METRICS.A[a])
);
// Scope Unchanged vs Changed use different formulas
let impact, score;
if (scope === 'U') {
impact = 6.42 * iscBase;
score = Math.min(impact + exploitability, 10);
} else {
impact = 7.52 * (iscBase - 0.029) - 3.25 * Math.pow(iscBase - 0.02, 15);
score = Math.min(1.08 * (impact + exploitability), 10);
}
return impact <= 0 ? 0 : Math.ceil(score * 10) / 10;
}
// Example: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H
// Network, Low complexity, No privs, No user interaction, Unchanged scope
// Full CIA impact → 9.8 Critical
cvssBaseScore('N', 'L', 'N', 'N', 'U', 'H', 'H', 'H'); // 9.8
Severity rating bands
| Score range | Severity | Example |
|---|---|---|
| 9.0 – 10.0 | Critical | Remote code execution without authentication |
| 7.0 – 8.9 | High | SQL injection requiring low privileges |
| 4.0 – 6.9 | Medium | Information disclosure requiring user interaction |
| 0.1 – 3.9 | Low | Reflected XSS with minimal impact |
| 0.0 | None | No impact |
WarningCVSS Base Score measures intrinsic severity, not actual risk. A 9.8 Critical vulnerability on an internal-only server with no internet exposure may be lower risk than a 6.5 Medium on your public-facing authentication endpoint. Always consider environmental context.
TipThe ShieldX CVSS Calculator computes v3.1 base scores with interactive vector selection, produces the vector string, and displays the severity rating — all in your browser.
Cookie security: HttpOnly, Secure, and SameSite
Three flags that prevent most cookie-based attacks
Cookies are the oldest web authentication mechanism and still the most widely deployed. They are also the attack surface for cross-site scripting (XSS) token theft, cross-site request forgery (CSRF), and session hijacking over insecure connections. Three Set-Cookie attributes address each of these vectors: HttpOnly, Secure, and SameSite.
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict; Max-Age=86400; Path=/; Domain=example.com
# Attribute breakdown:
# HttpOnly — JavaScript cannot access the cookie (document.cookie)
# Prevents XSS-based session token theft
# Secure — Cookie only sent over HTTPS
# Prevents interception over plaintext HTTP
# SameSite=Strict — Cookie never sent on cross-site requests
# Prevents CSRF completely
# SameSite=Lax — Cookie sent on top-level navigation (link clicks)
# Prevents CSRF on most endpoints (default in modern browsers)
# SameSite=None — Cookie sent on all cross-site requests
# Required for third-party cookies; must also set Secure
# Max-Age — Cookie lifetime in seconds (alternatively: Expires=date)
# Path — URL path scope for the cookie
# Domain — Domain scope (omit for host-only cookie)
Attack vectors and their mitigations
| Attack | How it works | Mitigation |
|---|---|---|
| XSS token theft | Malicious script reads document.cookie | HttpOnly flag |
| Session sniffing | Cookie intercepted over HTTP | Secure flag + HSTS |
| CSRF | Cross-site request carries victim's cookie | SameSite=Strict or Lax |
| Session fixation | Attacker sets a known session ID | Regenerate session ID on login |
| Cookie tossing | Subdomain sets cookie for parent domain | Avoid Domain attribute, use host-only cookies |
SameSite=None requires Secure in modern browsers. This means third-party cookies (analytics, embedded widgets) must be served over HTTPS. Chrome, Firefox, and Edge all enforce this. If you need cross-site cookies, set SameSite=None; Secure and ensure your site is HTTPS-only.
WarningThe __Host- prefix is a defense-in-depth measure. Cookies named __Host-session are restricted: no Domain attribute, Path=/, and Secure required. This prevents subdomain cookie tossing attacks. Use __Host- for all session cookies.
TipThe ShieldX Cookie Analyzer parses Set-Cookie headers, checks HttpOnly/Secure/SameSite flags, and scores cookie security posture. Use it to audit your application's cookie configuration.
CORS and cross-origin security
When browsers block requests — and when they should not
Cross-Origin Resource Sharing (CORS) is the browser mechanism that controls when JavaScript on one origin can make requests to a different origin. Without CORS, the same-origin policy blocks all cross-origin reads. CORS headers on the response tell the browser which origins are allowed, which methods are permitted, and whether credentials can be included.
The most dangerous CORS misconfiguration is Access-Control-Allow-Origin: * combined with Access-Control-Allow-Credentials: true. This combination is actually rejected by browsers (the spec forbids it), but some servers work around it by reflecting the request's Origin header back as the ACAO value. This effectively allows any website to make authenticated cross-origin requests — a complete same-origin policy bypass.
# Preflight request (OPTIONS) response headers
Access-Control-Allow-Origin: https://trusted.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
# Simple request (GET/POST with simple headers) — no preflight needed
# Server just needs to return:
Access-Control-Allow-Origin: https://trusted.example.com
# DANGEROUS — never do this:
Access-Control-Allow-Origin: * # allows any origin
Access-Control-Allow-Credentials: true # with credentials
# DANGEROUS — origin reflection:
# Server copies the Origin header value into ACAO
# This allows any website to make authenticated requests
CORS security rules
- Never reflect the Origin header into Access-Control-Allow-Origin — maintain an allowlist
- Never combine ACAO: * with Allow-Credentials: true — browsers block it, but don't try to work around it
- Whitelist specific origins, not patterns — "https://*.example.com" is not supported by the spec
- Minimize Access-Control-Allow-Methods — only list methods your API actually supports
- Set Access-Control-Max-Age to reduce preflight requests — 86400 (24h) is reasonable
- Treat CORS as browser-enforced, not server-enforced — curl and Postman ignore CORS entirely
WarningCORS is not an authentication mechanism. It prevents browsers from reading cross-origin responses, but it does not prevent the request from being sent. Your server must still authenticate and authorize every request independently of CORS headers.
TipThe ShieldX CORS Checker verifies Access-Control-* headers, checks Allow-Origin and Allow-Credentials combinations, lists allowed methods, and flags misconfigurations like origin reflection.
Have questions? We are here to help
Reach out anytime. We respond within 48 hours with a real answer from a real person.
No signup · No tracking · secure.toolly.site