Blog | G5 Cyber Security

Secure API Access with MD5 Hashing

TL;DR

This guide shows you how to secure your APIs using a simple but effective authentication and authorization method based on MD5 hashing. We’ll combine a user ID, secret key, the API endpoint being accessed, and the request payload into a hash for verification.

Step-by-Step Guide

  1. Understand the Concept
  • Client-Side Hash Generation
  • You’ll need a library or function to calculate MD5 hashes in your chosen programming language. Here are examples:

  • Server-Side Verification
  • On your server, implement the following steps for each API request:

    1. Extract the userid from the request (e.g., from headers or authentication tokens).
    2. Retrieve the user’s secret key from a secure storage location (database, configuration file – *never* hardcode it!).
    3. Extract the endpoint and payload from the request.
    4. Calculate the MD5 hash using the same formula as the client:
      data = userid + key + endpoint + payload
      hash = hashlib.md5(data.encode('utf-8')).hexdigest() #Python example
    5. Compare the calculated hash with the hash sent by the client in the request header (e.g., an X-Signature header).
    6. If the hashes match, authenticate the user and authorize access to the requested resource. Otherwise, reject the request with a 401 Unauthorized error.
  • Example Request Header
  • The client should include the generated hash in a custom header:

    X-Signature: <generated_hash>
  • Important Security Considerations
  • Exit mobile version