guideRequest signature in Java

This article presents a sample implementation of a request signature in Java.

# Dependencies

This example uses the util and crypto dependencies from the Java SDK.

# Example

The following simple example implements the algorithm described in the Request signature guide. The most important thing is to calculate HMAC-SHA-256 using any library using the given parameters in the correct order: method, url, timestamp, body.

The method parameter should be uppercase and the url should contain only the path from the URL, not the full URL address.

To verify the implemented request signature algorithm, you can use the data from the sample below. For the provided sample data, the correct request signature is 56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762.

import java.util.Formatter;
import java.util.Map;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Mac;

public class Main {
    private static final String API_SECRET = "SECRET";
    private static final String HMAC_SHA256 = "HmacSHA256";

    public static void main(String args[]) throws Exception {
        String method = "POST";
        String path = "/webhook?a=1";
        String bodyString = "{\"a\":1}";
        String timestamp = "1563276169752";

        String expectedSignature = "56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762";
        String signature = generateSignature(method, path, timestamp, bodyString, API_SECRET);

        System.out.println(signature.equals(expectedSignature));
    }

    private static String toHexString(byte[] bytes) {
        Formatter formatter = new Formatter();

        for (byte b : bytes) {
            formatter.format("%02x", b);
        }

        return formatter.toString();
    }

    public static String calculateHMACSHA256(String data, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), HMAC_SHA256);
        Mac mac = Mac.getInstance(HMAC_SHA256);

        mac.init(secretKeySpec);

        return toHexString(mac.doFinal(data.getBytes()));
    }

    private static String generateSignature(String method, String url, String timestamp, String body, String secret) throws Exception {
        String methodUpperCase = method.toUpperCase();
        String signatureData = methodUpperCase + url + timestamp;

        if (body != null) {
            signatureData += body;
        }

        return calculateHMACSHA256(signatureData, secret);
    }
}