Signing

Signing of the request body (payload) is needed in order to protect the integrity and the authenticity of the message. To compute a signature hash, The Kingdom Bank provides the Merchant a Signature Key.

You can view and manage your Signature Keys from the Merchant dashboard.

Every Merchant Account has at least one Signature Key used for both signing API requests and for receiving signed notifications from The Kingdom Bank. Every Signature Key has its own Key ID. When you sign a request, put the Key ID of the key you used in the X-Signature-Key-Id header. When The Kingdom Bank signs a response or a notification, it uses one of your active keys and sends its Key ID in the X-Signature-Key-Id header; always select the key by that ID.

The Signature Key itself is a unique piece of information generated with a CSPRNG; it is known both by the Merchant and The Kingdom Bank. The signature generation algorithm used is HMAC-SHA256. The generated hash is Base64-encoded and the result transmitted in the X-Signature header.

Briefly, the signature string is generated using the following functions: Base64(HMAC-SHA256(payload)).

The payload is the exact raw request body, as UTF-8 bytes, that you send. Do not re-serialize the JSON after signing. Only requests with a body are signed: GET requests need only X-Api-Key and X-Api-Secret. A missing X-Signature returns 1003, a missing X-Signature-Key-Id returns 1004, an unknown Key ID returns 1005, and a wrong signature returns 1002 (all 401).

Successful API responses are signed the same way: verify Base64(HMAC-SHA256(responseBody)) with the key named in the response's X-Signature-Key-Id header. Error responses are not signed.

Java

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public String signMessage(String body, String signatureKey) {
    try {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(signatureKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] hash = mac.doFinal(body.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(hash);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw new IllegalStateException("Unable to sign body", e);
    }
}