Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
An API token check that stops at the first wrong byte can reveal how much of a guessed token is correct. By sending many candidates and measuring tiny timing differences, an attacker may infer a bearer token or MAC one character at a time. The attack is statistical rather than guaranteed: network jitter, server load, rate limits and the endpoint’s design determine whether the signal is measurable remotely. The safe design is to compare canonical, equal-length byte values with a vetted constant-time primitive, handle length mismatches without a secret-dependent early return, and verify the exact bytes that were signed. Constant-time comparison does not replace replay protection, input validation or sound token storage, but it removes the prefix-length oracle created by ordinary equality checks.
What makes an ordinary token comparison leak information?
Most conventional string comparisons examine values from left to right and stop as soon as they find a mismatch. If the first byte differs, the function does very little work. If the first 20 bytes match and the 21st differs, it performs more work before rejecting the value. The difference may be only a few CPU instructions, but it is correlated with the length of the matching prefix.
As an Amazon Associate I earn from qualifying purchases.
Cloudflare describes the behavior plainly: “When strings are compared using the equality operator (== or ===), the comparison will end at the first mismatched character.” When the value being compared is a secret-derived token, that behavior turns elapsed time into an oracle. A candidate that takes slightly longer is not necessarily correct, but it may have matched one more character than the alternatives.
A constant-time comparison is designed to perform the same logical work for every pair of equal-length inputs, regardless of where they differ. It accumulates differences across the complete buffer and only then returns success or failure. “Constant time” is an implementation property, not a promise that an entire HTTP request takes a fixed number of milliseconds; parsing, database access, scheduling and network transport still vary.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
How can an attacker recover a token one character at a time?
The attacker needs an endpoint that accepts a secret-dependent value and produces a measurable success or failure response. The target might compare an API key, a bearer token, an HMAC, a webhook signature or another MAC-like value. The attacker then turns the comparison’s prefix leak into a sequence of guesses.
1. Find a measurable verification path
The attacker first identifies a request that reaches the secret comparison. Different status codes are useful, but they are not required; a timing difference alone can be enough. A path that performs expensive work after a successful check can obscure the signal, while a lightweight authentication failure may make the comparison easier to isolate.
Recommended Free Tools
2. Establish a baseline
Many requests with an invalid value reveal the normal distribution of response times. The attacker records median or trimmed-mean latency rather than trusting one sample. Measurements are usually grouped by candidate so that transient congestion, connection setup and garbage collection can be averaged out.
3. Guess the first byte
For a MAC represented as bytes, the attacker tries each possible value for the first byte while keeping the rest of the candidate fixed. Intel’s illustrative walkthrough tries all 256 byte values, retains the candidate with the longest measured comparison time, and then advances to the next byte. Text tokens use an analogous character alphabet, although the number of guesses depends on the allowed encoding.
4. Extend the prefix
Once a likely first byte is selected, the attacker keeps it and varies the second byte. A candidate with a correct two-byte prefix should, on average, reach the comparison later than one with only the first byte correct. The process repeats until the complete value is recovered or the attacker has enough of it to pass the check.
5. Confirm rather than trust a single winner
Noise can make the wrong candidate look slow. A careful attack re-tests the leading candidates, randomizes request order, and uses statistical methods to distinguish a persistent prefix signal from an outlier. There is no authoritative universal request count or success rate: the required volume depends on the implementation, network path and competing workload.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Can a remote attacker really measure this over HTTP?
Sometimes, but not automatically. PortSwigger’s analysis emphasizes the relationship between the timing signal and noise. A local process, a low-latency private network or a quiet service can expose a small difference more readily than a busy public endpoint. HTTP connection reuse, server-side queues, TLS processing, caches, autoscaling and unrelated application work all add variance.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Remote exploitability therefore needs to be stated carefully. A non-constant comparison is objectively a vulnerability in the code path even when no one has demonstrated a successful attack against a particular deployment. The 2026 Karakeep advisory illustrates this distinction: it identified non-constant comparisons in API-key and signed-token paths but reported that no live timing measurement had been performed against a running instance.
- Signal strength: the more work that depends on the matching prefix, the easier the difference is to separate from noise.
- Request access: an attacker needs a way to send enough verification attempts without being blocked by authentication gates, quotas or network controls.
- Endpoint consistency: stable routing and a repeatable code path help; load balancing and variable downstream work hurt.
- Observation quality: persistent connections and controlled measurement reduce transport variance, but cannot eliminate it.
- Defensive friction: rate limits, lockouts and monitoring raise the cost of measurement but do not repair the comparison.
Do not use “we could not reproduce it over the internet” as proof that the code is safe. Treat the timing flaw as real, then evaluate the deployment’s exposure separately.
Is == safe for HMACs, bearer tokens or API keys?
No. Ordinary equality is appropriate for non-secret values, but it should not decide whether an attacker-supplied value matches a secret or a secret-derived authenticator. The same warning applies to hand-written loops and low-level functions whose early-exit behavior has not been explicitly addressed.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problems| Comparison approach | Typical behavior | Use for secret verification? | Required review |
|---|---|---|---|
== or === |
Often stops at the first mismatch | No | Replace it with a vetted primitive |
| Hand-written byte loop | Easy to introduce an early return or compiler-sensitive optimization | No, unless a platform expert has verified the generated code and contract | Prefer the standard cryptographic API instead |
memcmp or equivalent |
Commonly returns at the first differing byte | No by default | Use a documented constant-time alternative |
crypto.timingSafeEqual |
Constant-time comparison for equal-length buffers; throws on unequal lengths | Yes, with safe length handling | Normalize representations before calling it |
hmac.compare_digest |
Designed for constant-time digest or token comparison | Yes | Use the same type and encoding on both sides |
MessageDigest.isEqual |
JVM API intended for digest comparison | Yes | Supply canonical byte arrays and review length behavior |
CryptographicOperations.FixedTimeEquals |
.NET constant-time byte comparison | Yes | Pass equal-length byte spans or arrays |
OWASP’s webhook guidance gives the operational rule: “Recompute the HMAC and compare it with a constant-time function such as hmac.compare_digest, crypto.timingSafeEqual, or MessageDigest.isEqual.” The primitive is only one part of the design; the bytes supplied to it must also be the bytes the sender intended to authenticate.
How should an HMAC or token check be implemented?
Build the verification path in a fixed order. Recompute the expected authenticator from the exact request representation, convert both values to the same canonical byte representation, make the comparison inputs a fixed size or otherwise handle unequal lengths without a secret-dependent early exit, and call the platform’s vetted primitive.
- Read the raw signed material. For a webhook, capture the exact request body bytes before JSON parsing. For a signed request, construct the exact covered components required by the protocol.
- Decode the supplied authenticator. Base64, hexadecimal and other encodings must be parsed strictly and consistently. Reject malformed syntax as an input error, not as a partially decoded value.
- Recompute the expected value. Use the correct secret, algorithm, key identifier and message coverage. Do not verify a parsed-and-reserialized object when the sender signed the original bytes.
- Normalize lengths safely. The comparison API must not throw on attacker-controlled length differences or return before the secret-dependent work is complete.
- Compare with a constant-time primitive. Return the authentication result only after the fixed-time comparison has finished.
- Apply policy checks separately. Check expiration, audience, scope, nonce or replay status after cryptographic verification, without treating those checks as a substitute for it.
Node.js example
Node’s crypto.timingSafeEqual requires equal-length buffers and throws otherwise. Hashing both canonical byte strings to a fixed-size digest gives the primitive equal-length inputs; the digest comparison then determines the result.
import { createHash, timingSafeEqual } from 'node:crypto';
function fixedDigest(bytes) {
return createHash('sha256').update(bytes).digest();
}
function tokenMatches(presented, expected) {
const candidateBytes = Buffer.from(presented, 'utf8');
const expectedBytes = Buffer.from(expected, 'utf8');
const candidateDigest = fixedDigest(candidateBytes);
const expectedDigest = fixedDigest(expectedBytes);
return timingSafeEqual(candidateDigest, expectedDigest);
}
This pattern prevents the API from throwing because the original strings have different lengths. In a protocol where the token’s exact length is part of the format, validate that format before verification or include a documented fixed-length encoding rule. If the secret length itself must remain hidden, do not add a separate early length check that reveals it through response timing.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Python example
import hashlib
import hmac
def token_matches(presented: bytes, expected: bytes) -> bool:
candidate_digest = hashlib.sha256(presented).digest()
expected_digest = hashlib.sha256(expected).digest()
return hmac.compare_digest(candidate_digest, expected_digest)
For an HMAC, compute the HMAC over the exact message bytes first, then pass the two resulting digests to hmac.compare_digest. Keep both operands as bytes; mixing text and bytes can create implicit encoding differences or an exception path that complicates verification.
Java and .NET examples
// Java
boolean valid = MessageDigest.isEqual(expectedMac, suppliedMac);
// .NET
bool valid = CryptographicOperations.FixedTimeEquals(expectedMac, suppliedMac);
Both examples assume that decoding, algorithm selection and length policy have already been handled. Keep the result as a boolean used by the authentication decision; do not log the supplied token or the computed MAC.
What should happen when the supplied and expected values have different lengths?
Unequal lengths are a frequent source of accidental leaks and runtime errors. A direct call to a primitive that requires equal lengths can throw, while an explicit if (candidate.length !== expected.length) return false can reveal the secret length if the expected value is secret.
The right handling depends on what is public. If the protocol specifies a fixed-size MAC, reject malformed encodings as format errors and ensure the cryptographic comparison itself always receives the fixed-size decoded value. For variable-length secrets whose length must not be disclosed, compare fixed-size digests of both values or use a library routine whose contract explicitly covers unequal lengths without a secret-dependent branch.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Do not pad values casually and then compare the padded buffers unless the padding rule, maximum size and processing cost are well defined. A naive scheme can introduce ambiguity, permit multiple encodings or create a new length-dependent operation. Whatever approach you choose, test empty input, overlong input, truncated encodings and every malformed representation.
Why do canonicalization and raw-byte handling matter?
Constant-time comparison cannot make two different messages equivalent. If a sender signs one byte sequence and the receiver verifies another, legitimate requests fail; if the receiver verifies only a normalized subset, an attacker may exploit the gap between what was signed and what the application processes.
- Do not parse JSON and serialize it again before verification unless the protocol explicitly defines canonical JSON.
- Preserve whitespace, field order and escaping when the signature covers the raw body.
- Use one declared character encoding, normally UTF-8 where the protocol specifies it, and reject ambiguous alternatives.
- Decode Base64 or hexadecimal strictly and normalize case only where the encoding specification permits it.
- Include the same method, path, query, headers and body components on both sides of a signed-request protocol.
OWASP’s webhook guidance specifically warns that re-serializing JSON, changing whitespace, reordering fields or changing encoding invalidates signatures. CSRF guidance likewise calls for an unambiguous encoding and comparison in the same representation.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Does a constant-time comparison stop replay attacks?
No. It addresses information leakage during equality testing, not reuse of a valid message. An attacker who captures a correctly signed request may replay it even when the signature check is perfectly constant-time.
Signed-request protocols should define a validity window and replay control. HTTP Message Signatures (RFC 9421) provides a framework for declaring covered components and validity parameters; applications still need to enforce them.
- Include a timestamp and reject requests outside a deliberately short clock-skew window.
- Include a nonce or unique request identifier and store recently accepted values for the lifetime of the window.
- Bind the signature to the intended method, authority, path and relevant headers so it cannot be moved to another operation.
- Use key identifiers and rotation rules so a compromised credential can be retired without ambiguity.
How can I audit an existing API for this flaw?
Start with code search, then verify the complete execution path. Look for equality operators, memcmp, string comparison helpers and custom loops wherever one operand comes from a request and the other comes from a secret, token store or MAC calculation.
Static review checklist
- Trace every API-key, bearer-token, webhook and signature verification path.
- Record the primitive, operand types, decoding step and unequal-length behavior.
- Confirm that the expected MAC covers the exact bytes and fields required by the protocol.
- Check whether malformed input, missing headers and wrong lengths take a visibly different path.
- Verify expiration, nonce and replay checks independently of the equality primitive.
Dynamic testing
Use a test environment with a fixed secret and generate candidates that differ at progressively longer prefixes. Collect many timings for each candidate, randomize test order and compare distributions rather than individual requests. The goal is to detect a statistically persistent prefix correlation, not to claim that a production attack will require a particular number of requests.
Repeat the test under realistic load, through the production proxy stack and with connection reuse enabled. If the signal disappears in a noisy environment, retain the code finding: noise changes exploitability, not the comparison’s semantics.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWhat defenses reduce risk while the code is being fixed?
Replace the comparison first; layered controls then limit the value of any remaining signal or stolen credential.
- Rate-limit verification attempts. Apply limits per account, key identifier, source and endpoint, while avoiding a policy that can be trivially bypassed through many addresses.
- Use short-lived credentials where practical. Rotation and expiration reduce the window in which an inferred token is useful.
- Monitor failures and near-misses. Bursts of invalid tokens, repeated prefix patterns and unusual geographic or client changes merit investigation.
- Avoid detailed error responses. Keep status and body behavior consistent for invalid credentials, without relying on response uniformity as the cryptographic fix.
- Protect token storage. Store a verifier or keyed digest when the protocol permits it, so a database read does not immediately reveal usable bearer values.
These measures are defense in depth. A rate limit can slow an oracle; it cannot turn an early-exit comparison into a constant-time one.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Which implementation is safer in a code review?
The strongest option is usually the highest-level verification routine whose documentation specifies canonical input handling and constant-time comparison. A low-level implementation can be correct, but it places more responsibility on your team to maintain length checks, encoding rules and compiler or runtime behavior.
| Review question | Safer answer | Warning sign |
|---|---|---|
| What performs the comparison? | A documented cryptographic fixed-time API | Equality operator, memcmp or custom loop |
| What happens on unequal lengths? | Fixed-size inputs or a documented non-leaking policy | Immediate return, exception or secret-dependent branch |
| What bytes are authenticated? | The exact raw message and declared protocol components | Parsed and reserialized data with undocumented normalization |
| Are encodings unambiguous? | Strict decoding into one canonical representation | Multiple spellings accepted for the same value |
| Are replays controlled? | Timestamp, nonce or equivalent validity and uniqueness checks | Signature validity treated as proof of freshness |
| How is exposure limited? | Rate limits, rotation, monitoring and minimal error detail | Reliance on obscurity or a single control |
What is the practical fix for a vulnerable endpoint?
Deploy the constant-time comparison as a focused security patch, then test the protocol around it. Preserve the existing token format unless changing it is necessary, because an encoding migration can create compatibility and rollback problems.
- Identify every secret comparison, including shared libraries and middleware.
- Choose the platform primitive and define the byte representation it accepts.
- Write tests for correct values, one-byte changes at each position, wrong lengths, empty values and malformed encodings.
- Verify that the raw message, algorithm, key identifier and covered fields are identical on both sides.
- Add or confirm timestamp, nonce and replay controls for signed requests.
- Roll out with monitoring for authentication failures and latency anomalies, without logging secrets.
- Rotate credentials if the vulnerable endpoint was exposed long enough that measurement or token theft is plausible.
Frequently Asked Questions
What is the difference between constant-time comparison and encryption?
Encryption hides message contents while data is in transit or storage. Constant-time comparison protects the verification operation from revealing information through its duration; it does not encrypt a token or make a leaked token unusable.
Should I hash an API token before storing it?
For bearer tokens, storing a verifier such as a keyed digest can reduce the impact of a database disclosure, provided the server can still verify presented tokens. Use a construction and rotation process appropriate to the token’s entropy and protocol, and do not treat hashing as a replacement for constant-time comparison.
Can response-status differences make a timing attack worse?
Yes. Distinct status codes or response bodies can provide a clearer oracle than timing, while expensive success-only work can add noise. Keep authentication failures intentionally uniform where feasible, but fix the comparison even when the responses already look identical.
Does TLS prevent timing attacks on token checks?
No. TLS protects confidentiality and integrity on the network path, but the client that sends requests can still observe when its own responses arrive. Encryption of the connection does not remove server-side timing differences.
Free tools Windows power users keep installed
One-click scans. No signup required.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

