This guide provides a detailed explanation of how to generate an authorization header for an API request using cryptographic operations. The process involves creating a JSON request body, hashing an API key with SHA-256, and then using that hash to compute an HMAC-SHA256 signature of the body. The resulting signature (as a hexadecimal string) becomes the value of the Authorization header.
Prerequisites
- API Key and Vendor Details: You'll need a secret VENDOR_API_KEY (a string) and VENDOR_NUMBER (a string identifying your account). Vendor API key and Vendor number are provided by Evrotrust.
- Best Practices:
- Store the API key securely.
- Never commit secrets to version control.
Step 1: Construct the Request Body
- Create a JSON object with the structure required by the endpoint.
- Serialize the object to a JSON string. Ensure consistent formatting (e.g., no unnecessary spaces or sorting changes) to avoid signature mismatches.
Step 2: Compute the SHA-256 Hash of the API Key
- Take the raw API key string.
- Encode it as UTF-8 bytes.
- Apply SHA-256 hashing to produce a 32-byte (256-bit) digest. This digest acts as a derived secret key for the HMAC, enhancing security.
Step 3: Compute the HMAC-SHA256 Signature
- Use the SHA-256 digest from Step 2 as the secret key.
- Use the JSON string from Step 1 as the message.
- Compute the HMAC-SHA256, which produces another 32-byte digest.
- Convert this digest to a lowercase hexadecimal string (64 characters).
Step 4: Set the Authorization Header
- Use the hexadecimal string as the value for the Authorization header in your HTTP request, e.g.
- DATA_TO_HEX
7b2276656e646f724e756d626572223a2261685a736d52486244484c3654654544222c22757
365724964656e74696669636174696f6e4e756d626572223a2238363131303438393830227d - VENDOR_API_KEY_SHA256 = SHA256(VENDOR_API_KEY)
05f1a4f713f589ec6126e6161255649eca830a32ce55f3ec2fa9268c9add8d69 - AUTHORIZATION = HMAC(SHA256, DATA_TO_HEX, VENDOR_API_KEY_SHA256)
c38babb38a5498deae40e8d71c101156242ab6a6f019290d16b62e0da9ad2cc2
- DATA_TO_HEX
