# API Security

In cryptography, an **HMAC** (sometimes extended as either keyed-hash message authentication code or hash-based message authentication code) is a specific type of message authentication code (MAC) involving a cryptographic hash function and a secret cryptographic key.

<figure><img src="/files/exTaQKVNFGpGK1vseGcS" alt=""><figcaption><p>API Security Protocol Overview</p></figcaption></figure>

HMAC protocol is widely used in the industry and is one of the key protocols for the Web Payments standard, which [W3.org](https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures-05) issues.

**API key** creation happens upon customer creation. Our system ensures **API security using API keys and HMAC secrets**. API keys are random strings that are almost impossible to brute force. However, these keys need an additional layer of security. The system transmits API keys to the user with an HTTPS request, and the system has to display these values on the screen. This kind of communication makes them vulnerable. With **HMAC**, the system uses a non-exposable entity when intercommunicating with the customer.

{% hint style="info" %}
Customers use our endpoint to save their own HMAC secrets. They must persist this secret on their ends and use it to sign their payloads with each **POST** request. The system also uses an identical approach to verify the authenticity of the customer's requests. Using this procedure, both parties are aware of the same secret. Since the customers transfer this secret once, before either party starts communicating, this is the safest way for us.
{% endhint %}

**Hmac secret** should be stored securely, preferably in an encrypted database. Before communicating with our system, the calling end must enable **HMAC security** by submitting the **HMAC secret**. Otherwise, the system refuses the request with a response of **HTTP 400 (Bad Request)**. Only the communicating ends know this secret. You can use **UUID version 4** while generating a safe **HMAC secret**.&#x20;

It is advisable to update this secret periodically **when there is no ongoing traffic.** This step will help ensure maximum protection and minimize the likelihood of unauthorized access or security breaches.

[You can enable or update HMAC security using this endpoint (HMAC).](/security/enable-update-hmac.md)

## Signing The Payload

After enabling **HMAC**, the customers must sign their POST requests with the **HMAC, Sha-2, 512-bit hash algorithm**, and the result must be **base64** encoded. The customers must pass this **signed base64 encoded hash** with the header **x-payload-hash** to our API endpoints for each **POST** request.

Here is our TypeScript example for opening a deposit tracking session. In this example, you can learn how to calculate an HMAC and pass this hash for your post requests.

<pre class="language-typescript" data-line-numbers><code class="lang-typescript">const hmacSecretKey = 'YOUR HMAC SECRET Key';
const xApiKey = 'YOUR API KEY'

const payloadPgCreateSessionForAUser = {
    userId: 'YOUR UNIQUE USER ID',
    userName: 'YOUR USER NAME',
    userNameSurname: 'THE NAME AND SURNAME OF YOUR USER',
    sessionDefaultLanguage: 'en',
    sessionDefaultFiatCurrency: 'USD',
    minPaymentAmountInUSD: 0.5
};

const body = JSON.stringify(payloadPgCreateSessionForAUser);
const xPayloadHash = createHmac('sha512', hmacSecretKey).update(body)
                .digest('base64');

try {
    const sessionCreationResult = await axios.post(
        'https://api-prod.alfa-instap-cpt.uk/pgpub/session', body,
        {
            timeout: 6000,
            headers: {
                "content-type": "application/json",
                "x-api-key": xApiKey,
                "x-payload-hash": xPayloadHash,
            }
        }
    );
    console.log(sessionCreationResult.data);
} catch (error) {
    console.log(error);
    throw new Error('Session creation failed');
<a data-footnote-ref href="#user-content-fn-1">}</a>
</code></pre>

{% hint style="warning" %}
You should first **JSON.stringify** the body and then calculate the **x-payload-hash** using this stringified body. After that, pass this hash onto your **x-payload-hash** header and the stringified body (which you have used to calculate HMAC) for your POST requests.
{% endhint %}

{% hint style="warning" %}
The result of the HMAC calculation should be **base 64** encoded.
{% endhint %}

#### The Structure of a POST request

{% code overflow="wrap" %}

```bash
curl --request POST \
  --url https://api-prod.alfa-instap-cpt.uk/pgpub/session \
  --header 'content-type: application/json' \
  --header 'x-api-key: REPLACE WITH YOUR_API_KEY' \
  --header 'x-payload-hash: REPLACE WITH YOUR CALCULATED HMAC' \
  --data 'REQUEST PAYLOAD'
```

{% endcode %}

[^1]:


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.cryptobox.ninja/security/api-security.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
