Cryptography Training

Exercise: API Request Signing

In this activity, you will use HMAC (Hash-based Message Authentication Code) to ensure data integrity.

Scenario: You are building a secure payment API. When a user sends a payment request (e.g., "Pay $100"), you need to prove that a hacker didn't intercept it and change it to "Pay $1000".

The Difference

Unlike Hashing (which just scrambles data), HMAC uses a Secret Key. Only someone with the key can generate a valid signature.

Your Task

Complete the sign_message function:

  1. Encode Data: Ensure both the secret_key and message are bytes (use .encode()).
  2. Generate HMAC: Use hmac.new(key, msg, hashlib.sha256).
  3. Return Hex: Return the .hexdigest() of the HMAC object.
PYTHON EDITOR (security_signer.py) Engine: Initializing...
1
SECURITY CONSOLE
Ready...
from js import window, document import hashlib import hmac window.python_is_ready = True try: document.getElementById("engine-status").innerHTML = "Engine: Python Active" except: pass def python_test_logic(user_code): results = [] def add_log(msg, type="normal"): results.append({"msg": msg, "type": type}) add_log("[SYSTEM] Verifying Signature Logic...", "system") test_env = {'hashlib': hashlib, 'hmac': hmac} try: exec(user_code, test_env) if "sign_message" not in test_env: add_log("[!] Error: Function 'sign_message' not found.", "fail") return results, "FAILED" func = test_env["sign_message"] # TEST 1: Basic Signature Generation add_log("--- TEST 1: Generating Signature ---", "system") key = "mySecretKey" msg = "Transfer $100" try: user_sig = func(key, msg) except TypeError: add_log(" -> FAIL: Type Error. Did you forget .encode()?", "fail") return results, "FAILED" if not isinstance(user_sig, str): add_log(f" -> FAIL: Expected string return, got {type(user_sig)}", "fail") return results, "FAILED" # Calculate Correct HMAC correct_sig = hmac.new(key.encode(), msg.encode(), hashlib.sha256).hexdigest() if user_sig == correct_sig: add_log(" -> PASS: Signature generated correctly.", "pass") else: add_log(" -> FAIL: Signature mismatch.", "fail") add_log(f" Exp: {correct_sig}", "fail") add_log(f" Got: {user_sig}", "fail") return results, "FAILED" # TEST 2: Integrity Check (Tampering) add_log("--- TEST 2: Tamper Detection ---", "system") tampered_msg = "Transfer $1000" # Hacker added a zero tampered_sig = hmac.new(key.encode(), tampered_msg.encode(), hashlib.sha256).hexdigest() if user_sig != tampered_sig: add_log(" -> PASS: Changed message produced different signature.", "pass") add_log(" SUCCESS: Integrity mechanism is working.", "pass") return results, "PASSED - Secure" else: add_log(" -> FAIL: Tampered message has same signature!", "fail") return results, "FAILED" except Exception as e: add_log(f"[!] Runtime Error: {e}", "fail") return results, "ERROR" return results, "UNKNOWN" window.python_test_runner = python_test_logic