HMAC Implementation - Problem

Implement HMAC (Hash-based Message Authentication Code) using a custom hash function. HMAC is a cryptographic authentication technique that combines a secret key with a message to produce a hash-based authentication code.

Your task is to:

  • Implement a simple custom hash function
  • Use this hash function to compute HMAC according to the standard algorithm
  • Return the final HMAC value as a hexadecimal string

The HMAC algorithm works as follows:

  1. If the key is longer than the hash block size, hash it to reduce its size
  2. If the key is shorter than the block size, pad it with zeros
  3. Create inner and outer padding by XORing the key with specific constants
  4. Compute the inner hash: hash(inner_pad + message)
  5. Compute the outer hash: hash(outer_pad + inner_hash)

Custom Hash Function: Use a simple polynomial rolling hash with prime number 31 and modulo 2^32.

Constants:

  • Block size: 64 bytes
  • Inner pad byte: 0x36
  • Outer pad byte: 0x5C

Input & Output

Example 1 — Basic HMAC
$ Input: key = "secret", message = "hello"
Output: "8b9a4c7d"
💡 Note: Using key 'secret' and message 'hello', the HMAC algorithm creates inner and outer padded keys, computes two hash rounds, and returns the final authentication code
Example 2 — Short Key
$ Input: key = "key", message = "data"
Output: "f2e1d8c5"
💡 Note: Short key 'key' gets padded with zeros to 64 bytes, then HMAC process generates the authentication code for message 'data'
Example 3 — Long Key
$ Input: key = "verylongkeythatexceedstheblocksizeandneedstobehashedfirst", message = "test"
Output: "a7c9b1e4"
💡 Note: Long key gets hashed first to reduce its size, then padded and processed through standard HMAC algorithm

Constraints

  • 1 ≤ key.length ≤ 1000
  • 1 ≤ message.length ≤ 1000
  • Key and message contain only ASCII characters

Visualization

Tap to expand
INPUTALGORITHMRESULTKey: "secret"Message: "hello"Input data requiringsecure authentication1Key PreparationPad/hash key to 64 bytes2XOR PaddingCreate inner (0x36) & outer (0x5C)3Inner HashHash(inner_key + message)4Outer HashHash(outer_key + inner_hash)HMAC Result8b9a4c7dSecure authenticationcode (hexadecimal)Key Insight:Double-layer hashing with XOR padding creates cryptographically secure authentication that prevents forgeryTutorialsPoint - HMAC Implementation | Cryptographic Authentication
Asked in
Google 25 Amazon 18 Microsoft 22 Meta 15
27.6K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen