Skip to content
API Security Deep Dive: Signatures, Timestamps, Nonces & Replay Prevention

API Security Deep Dive: Signatures, Timestamps, Nonces & Replay Prevention

This comprehensive guide answers 12 critical API security questions covering HMAC signatures, timestamp and nonce replay prevention, constant-time comparison against timing attacks, Redis SETNX atomic operations, appId/appSecret management, and key rotation strategies for robust API protection.

CodeSmart Hoops
CodeSmart Hoops
CodeSmart Hoops

API Security & Signature Replay Protection: 12 Interview Questions

This article serves as a companion self-test for "API Interface Security & Signature Replay Protection Complete Analysis," covering 12 interview questions with reference answers. Tags: interface signature, HMAC, replay prevention, nonce, timestamp, appId/appSecret, constant-time comparison, idempotency.

Q1: Why Is access_token Alone Insufficient? What Problems Does Interface Signature Solve?

Three Vulnerabilities of Token Authentication:

Tampering : Man-in-the-middle changes amount=100 to amount=1; token remains valid, backend executes anyway

Replay : Intercept old request and resend verbatim; request appears legitimate, backend executes again (e.g., duplicate charge)

Token Misuse : Leaked token allows anyone to call; cannot distinguish legitimate caller

Problems Solved by Interface Signature: access_token only proves "has permission to call," not "request content unmodified, not a replay, genuinely from authorized caller." Interface signature (HMAC) + timestamp + nonce trio prevents tampering, long-window replay, and short-window replay respectively, proving request integrity, freshness, and source legitimacy.

Key Insight: Login authentication (token) governs "who you are and what permissions you have"; interface signature governs "whether request is tampered/replayed/impersonated." They are separate defense lines; both are required.

Q2: Why Must Signature Cover method+path+query+body Entirely? Is Signing Only Body Enough?

Vulnerabilities of Signing Only Body: Attacker can modify parts outside body:

Change URL: /api/query → /api/delete; body unchanged, signature still passes

Change query param: id=1 → id=2; body unchanged, signature still passes

Change HTTP method: GET → DELETE; body unchanged, signature still passes

Correct Practice: Signature must cover method + path + query (sorted) + body + app_id + timestamp + nonce entirely. Any field changed alters the string-to-sign, signature mismatch, tampering detected.

Industry-Standard Concatenation Rule:

HTTP_METHOD + "
"
+ URL_PATH + "
"
+ Sorted query parameters (by key lexicographically) + "
"
+ body + "
"
+ app_id + "
"
+ timestamp + "
"
+ nonce

Reason for Sorting: Both caller and callee must construct identical string-to-sign; query parameter order inconsistency would produce different strings and signature mismatch. Lexicographic key sort guarantees consistency.

Reason for Newline Separators: Prevent concatenation ambiguity — e.g., a=1 + b=2 without delimiter could produce ambiguous string; newlines make boundaries explicit.

Q3: What Replay Attacks Do Timestamp and Nonce Each Prevent? Why Must They Work Together?

Mechanisms:

Timestamp prevents long-delay replay: request carries timestamp; reject if >5 minutes

Nonce prevents replay within validity window: one-time random number; reject if already used

Why They Must Combine:

Timestamp only, no nonce: Replay within 5 minutes — timestamp still valid, undetectable

Nonce only, no timestamp: Nonce would need permanent storage (unknown when replay occurs), storage explosion

Combined Solution: Timestamp limits validity window (5 minutes); nonce only stores within validity window (5-6 minute TTL). Timestamp blocks replays outside window; nonce blocks replays inside window; seamless coverage with controllable nonce storage (only 6 minutes).

TTL Setting: Nonce storage duration slightly exceeds timestamp validity (e.g., validity 5 minutes, nonce stored 6 minutes) ensuring all in-window replays caught by nonce, no gaps.

Q4: Why Must Nonce Replay Prevention Use SETNX Atomic Operation? What Is Wrong with Check-Then-Set?

Check-Then-Set Concurrency Vulnerability:

Request A: GET nonce → not exist → (not yet SET)
Request B: GET nonce → not exist → (A not yet SET, B also sees not exist)
Request A: SET nonce
Request B: SET nonce
Both requests pass, replay succeeds

Under concurrency, "check then set" has a time window — two identical requests may both see "not exist" then both set, allowing replay.

SETNX Atomic Operation:

if (!nonceBucket.setIfAbsent("1", NONCE_TTL)) {
    throw new ApiException(401, "Duplicate request");
}
setIfAbsent

(Redis SETNX) is atomic — "check + record" in one step. First request sets successfully; second request set fails, eliminating concurrency window.

Key Point: Nonce replay prevention must use atomic operations; check-then-set has concurrency vulnerability.

Q5: Why Must Signature Comparison Use Constant-Time Comparison? What Is a Timing Attack?

Timing Attack Principle: Standard String.equals returns false at first differing character. Attacker measures response time to brute-force signature character by character — correct first character yields slightly slower response, incorrect yields faster; thus each position deduced.

Attacker tries signature:
1st char guessed correct → comparison proceeds to 2nd char → response slightly slower
1st char guessed wrong → returns at 1st char → response slightly faster
Thus brute-force position by position, complexity reduced from O(16^32) to O(16*32)

Mechanism: equals is "short-circuit" — returns on first difference, skipping rest. Response time leaks "how many leading chars match." Attacker fixes first char (slower response when correct), then second, etc., reducing exponential difficulty to linear.

Constant-Time Comparison: Regardless of difference position, always traverse entire string, consistent duration:

private boolean constantTimeEquals(String a, String b) {
    if (a.length() != b.length()) return false;
    int result = 0;
    for (int i = 0; i < a.length(); i++) {
        result |= a.charAt(i) ^ b.charAt(i); // XOR accumulate per char
    }
    return result == 0; // all same → result==0
}

Key Point: Any comparison involving secrets/signatures/tokens/hashes must use constant-time comparison to prevent timing attacks. This is a fundamental secure coding principle.

Q6: Difference Between HMAC Symmetric Signature and Asymmetric Digital Signature? Applicable Scenarios?

Comparison:

Symmetric (HMAC) : Algorithm HMAC-SHA256; shared secret; non-repudiation ❌ (both parties hold key, cannot prove who signed); high performance; applicable to internal systems, open platforms

Asymmetric : Algorithm RSA, ECDSA; caller private key signs, callee public key verifies; non-repudiation ✅ (private key unique, signer cannot deny); lower performance; applicable to finance, contracts, non-repudiation required

Key Differences:

HMAC: both parties share key, sign and verify with same key, high performance, but no non-repudiation — both hold key, disputes cannot prove which party signed

Asymmetric: private key unique (only caller holds), sign with private key, verify with public key, signer cannot deny, but lower performance

Applicable Scenarios:

Open platforms, internal systems: HMAC (sufficient and efficient, non-repudiation not required)

Finance, contracts, compliance: Asymmetric signature (non-repudiation is hard requirement)

Q7: Difference Between Nonce Replay Prevention and Business Idempotency? Relationship?

Comparison:

Nonce : prevents malicious replay (attacker intercepts and resends); gateway layer; request-level (reject duplicate requests)

Business Idempotency : prevents network retry duplicates (caller actively resends); business layer; business-level (duplicate execution yields same result)

Differences:

Nonce: "reject duplicate requests," fast fail, prevents attacker malicious replay (short-term high frequency)

Idempotency: "duplicate execution produces no side effects," prevents network instability causing caller retry (legitimate resend)

Relationship: Complementary, not substitutive. Nonce at gateway quickly rejects malicious replays; idempotency at business layer ensures even if duplicate requests slip through (nonce missed, e.g., cross-instance), business result remains consistent. Payment interfaces need both — nonce prevents malicious replay charges, business idempotency (via unique business order constraint) prevents network retry duplicate charges.

Why Nonce Cannot Catch All Duplicates:

Multi-instance deployment: requests may hit two instances simultaneously, nonce check has microsecond window

After nonce expires (6 minutes), legitimate retry treated as new request

Hence critical interfaces require both.

Q8: Roles of appId and appSecret in Open Platforms? Why Must appSecret Never Be Transmitted?

Credentials:

appId : identifies caller identity; public (can be in Header)

appSecret : key for computing signature; absolutely secret (never transmitted)

Why appSecret Cannot Be Transmitted:

appSecret used locally to compute HMAC signature; both caller and callee use same appSecret to compute

Caller computes signature with appSecret, sends request only transmitting signature, not appSecret

Backend looks up appSecret by appId, recomputes signature for comparison

appSecret never on network; intercepted requests yield no appSecret

Why Not Transmit appSecret After Looking Up by appId: If appSecret transmitted, man-in-the-middle intercepts and can forge arbitrary signatures, breaking signature mechanism. appSecret must exist only locally on both ends, never on network.

Key Management: appSecret not in code (stored in config center/Vault), rotated periodically, supports multi-version key coexistence period.

Q9: Why Store Nonce in Redis Instead of Database? How to Set TTL?

Why Redis:

High-frequency read/write: Nonce read/write per request; database cannot handle (thousands to tens of thousands per second)

Short-term validity: Nonce only needs storage for validity window (5-6 minutes); Redis TTL auto-expires cleanup, no manual deletion

Atomic operations: Redis SETNX atomic "check+record"; database requires unique constraint + transaction, complex and slow

Performance: Redis sub-millisecond; database millisecond-level; auth path latency-sensitive

TTL Setting: Nonce storage duration slightly exceeds timestamp validity . E.g., timestamp validity 5 minutes, nonce stored 6 minutes. This ensures:

In-window replays: nonce still present (6-minute TTL), detected

Out-of-window replays: timestamp blocks first, nonce expiry irrelevant

Seamless coverage, auto-expiry cleanup, controllable storage

Key Point: Redis for nonce satisfies performance and feature requirements simultaneously — high frequency, atomic, auto-expiry; database satisfies none.

Q10: Is Interface Signature Still Needed with HTTPS? What Does HTTPS Not Prevent?

Yes, HTTPS Cannot Replace Interface Signature.

HTTPS Prevents: Eavesdropping and man-in-the-middle tampering in transit. HTTPS encrypts transport channel; middleman sees no plaintext and cannot modify.

HTTPS Does NOT Prevent:

Caller self-replay (intercept and resend verbatim) ❌ Request legitimate, HTTPS does not intercept

Token misuse after leak ❌ Token valid, HTTPS does not verify "is legitimate caller"

Caller tampers own request parameters ❌ HTTPS prevents middleman, not caller self-modification

Packet capture tools (Charles) decrypt on client side ⚠️ Client trusts capture cert, HTTPS bypassed

Interface Signature Covers These Gaps:

Signature prevents tampering (parameter change → signature mismatch)

Nonce + timestamp prevent replay

appSecret signature prevents impersonation (without appSecret cannot compute signature)

Key Insight: HTTPS secures the "transport channel"; interface signature secures the "request itself" (integrity, freshness, source). Different layers; both required. Open platform standard: HTTPS + OAuth2 + Interface Signature, none optional.

Q11: Why Is Nonce TTL Slightly Longer Than Timestamp Validity? Problems If Too Short or Too Long?

Reason for Slightly Longer: Ensure all in-window replays caught by nonce, seamless coverage.

Too Short Problem: If nonce TTL shorter than timestamp validity (e.g., validity 5 min, nonce 4 min), attacker intercepts request, waits 4 min 30 sec, replays — timestamp still valid (not yet 5 min), but nonce expired and treated as new request, replay succeeds. Gap appears: "timestamp didn't catch, nonce didn't catch."

Too Long Problem: If nonce TTL far exceeds validity (e.g., store 1 hour), security-wise fine (extra storage just wastes memory), but wastes storage — only need store in-window potential replays; extra 55 minutes useless data. High QPS makes waste significant.

Correct Setting: Nonce TTL slightly longer than timestamp validity (e.g., validity 5 min, nonce 6 min), extra 1 minute as buffer ensuring in-window replays still have nonce present.

Seamless Logic:

In-window (0-5 min) replays: nonce still present (6 min TTL), blocked

Out-of-window (5+ min) replays: timestamp blocks first, nonce expiry irrelevant

Seamless, no gaps

Q12: How to Rotate appSecret? Why Not Cut Over Directly?

Why Not Direct Cutover: During rotation, requests signed with old key may still be in flight (network latency, caller retries). If old key immediately revoked and only new key accepted, these legitimate requests rejected, causing business disruption. Callers also need time to update local appSecret config; instant full switch impossible.

Multi-Version Key Coexistence Solution:

Generate new key: Associate new appSecret with appId; old appSecret retained

Coexistence verification: During verification, iterate valid key list; any match passes — new-key-signed verified with new key, old-key-signed with old key, both work during transition

Callers gradually switch: Callers update local config to use new key for signing; new requests use new key

Retire old key after transition: Monitor old key usage drop to zero, then delete old appSecret

public String findSecretByAppId(String appId) {
    // Return current valid key list (new and old coexist)
    List<AppCredential> creds = appRepo.findActiveByAppId(appId);
    // Verification tries each; any match passes
    ...
}

Rotation Frequency: Typically quarterly, or immediately upon suspected leak.

Coexistence Period: Usually 1-2 weeks, sufficient for all callers to switch. Monitor old key usage; retire only after zero.

Key Insight: Key rotation is "gradual transition," not "instant switch." Multi-version coexistence is core to smooth rotation — both old and new verifiable, giving callers switch time, monitoring old key exit before cleanup.

References

API Interface Security & Signature Replay Protection Complete Analysis — companion original article

OWASP API Security Top 10 — Top 10 API Security Risks

HMAC RFC 2104 — HMAC Standard Specification

OAuth2 & OIDC Complete Analysis — OAuth2 Access Authentication

Anti-Packet Capture & Data Security Complete Analysis — Client Anti-Capture

Password Security & Encrypted Storage Complete Analysis — Constant-Time Comparison & Timing Attacks

Alibaba Cloud ACS3 Signature Spec / Tencent Cloud TC3-HMAC-SHA256 — Industry Signature Standards Reference

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

timestampIdempotencyAPI SecurityHMACreplay attacknonceTiming AttackKey Rotation
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.