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:
- If the key is longer than the hash block size, hash it to reduce its size
- If the key is shorter than the block size, pad it with zeros
- Create inner and outer padding by XORing the key with specific constants
- Compute the inner hash: hash(inner_pad + message)
- 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code