How to sign your message with HMAC + SHA256 in Python and Java

Natthapon Pinyo
2 min readMay 15, 2024

--

Sign a request is a one of simple solution to secure your APIs. This short guide will show you how easy to implementation this mechanism using HMAC and SHA256 in Java and Python programming languages.

Key Concept

Secret Key — a secretly shared value between server and client
This value can be anything, but must be a same value when perform signing.

Content/Message — a value to be signed/hashed.

Signing/Hashing — a process on client/consumer side to convert a content into some hashed data. Secret Key and Content will be involved in this step.

Verification — a process on server/provider side to do almost the same as client side. Calculating hashed value using same Secret Key and compare with the one sent from the client.

Implement using Java

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public static String hmacSha256(String key, String message) throws Exception {
Mac sha256Hmac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256Hmac.init(secretKey);
byte[] hmacData = sha256Hmac.doFinal(message.getBytes("UTF-8"));

return bytesToHex(hmacData);
}

private static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}

return hexString.toString();
}

public static void main(String[] args) throws Exception {
String secretKey = "YOUR_SECRET_KEY";
String content = "YOUR_CONTENT";
String hashed = hmacSha256(secretKey, content);
}

Implement using Python

import hmac
import hashlib

def hmac_sha256(key, message):
return hmac.new(
key.encode("utf-8"),
message.encode("utf-8"),
hashlib.sha256
).hexdigest()

def main():
secret_key = "YOUR_SECRET_KEY"
content = "YOUR_CONTENT"
hashed = hmac_sha256(secret_key, content)

Example use-case — Secured API

  1. Client — calculate hashed values from HTTP Request Body and Secret Key.
  2. Client — attach hashed value in HTTP Request Header.
    For example Authorization: {{hashed}}
  3. Client — submit API request
  4. Server — receive API request
  5. Server — read HTTP Request Body and calculate hashed value with the same Secret Key
  6. Server — Compare a received hashed value with computed hashed from step 5.
    If match, the verification is pass and continue the rest of API business logic.
    Otherwise, reject the request. For example return HTTP 401 Unauthorized

That’s it

Happy coding !

--

--