00:00

#0706

Hash Length Extension

Medium+150 XPA02:2021 Cryptographic FailuresCWE-327
HMACHash Length ExtensionMAC Forgery

Scenario

Your API signs request bodies so the server can verify they weren't tampered with in transit.

The current implementation computes `sha256(secret + message)` and sends the hex digest as an `X-Signature` header.

Because SHA-256 is a Merkle-Damgård hash, an attacker who intercepts a valid `(message, sig)` pair can craft a valid signature for `message || padding || extension` without knowing the secret — a classic Hash Length Extension attack.

The fix is to use HMAC-SHA256, which is provably immune to this attack.

Hash length extension attacks have been exploited in real APIs (Flickr, Vimeo, Last.fm) to forge signed requests. Using HMAC costs nothing but prevents an entire class of cryptographic forgery.

Your Tasks

  1. Replace the plain `sha256(secret + message)` MAC with a proper **HMAC-SHA256** using the language's standard library.
  2. The function signature stays the same: `sign(secret, message) -> str` — returns the lowercase hex MAC.
  3. Do NOT change the function signature or return type.

Examples

Example 1Vulnerable — sha256 concatenation

sign('key', 'amount=100')
// returns sha256('key' + 'amount=100') — forgeable!

Example 2Fixed — HMAC-SHA256

sign('key', 'amount=100')
// returns HMAC-SHA256('key', 'amount=100') — secure

Constraints

  • Return a 64-character lowercase hex string.
  • Use the standard library HMAC implementation — do not roll your own.
  • The secret and message should both be treated as UTF-8 when encoding to bytes.

Hint

References

solution.js
Ln 1, Col 1UTF-8JavaScript
Sandbox ready
0/0/0not run