# Signature Generation and Verification

## Working With Signature

We use signature when data authenticity must be ensured before we process it, In such case you will need to generate signature and it into request body. In some cases we may also provide the signature in response which you can validate to ensure that the data you have received has not been ultered on the way.

You have to use your[ Encryption Key](/technical-guide/web-integration/checkout-integration/web-integration-encryption.md) to generate or validate the signature.

### **Generation of Signature**

#### **P**seudo Code

```
Function generateSignature(Argument requestBody, Argument apiSecret)
	dataString: Stores the string genereated from request body
	signature: To store the generated signature

	For each KEY1 and VALUE1 in requestBody, do
		If VALUE1 is Array Then
			For each KEY2 and VALUE2 in VALUE1, do
				APPEND VALUE2 to dataString
				APPEND '|' to dataString
			EndFor
		Else
			APPEND VALUE1 to dataString
			APPEND '|' to dataString
		EndIf
	EndFor

	APPEND '#' to dataString
	signature = HASH_HMAC_SHA_256(dataString, apiSecret)
	return signature
End function
```

{% tabs %}
{% tab title="PHP" %}

```php
public function generateSignature($apiSecret, $requestBody) {
    $dataString = '';

    foreach ($requestBody as $key => $value) {
        if (is_array($value)) {
            foreach ($value as $_key => $_value) {
                $dataString .= $_value;
                $dataString .= '|';
            }
        } else {
            $dataString .= $value;
            $dataString .= '|';
        }
    }

    $dataString .= '#';

    $signature = hash_hmac('sha512', $dataString, $apiSecret);
    return $signature;
}
```

{% endtab %}

{% tab title="Java" %}

```java
public String generateSignature(String apiSecret, Map<String, String> requestBody) {
    try {
    String[] signature = { "" };
    requestBody.forEach((key, value) -> {
    signature[0] += value;
    signature[0] += "|";
   
            });
    signature[0] += "#";
    return this.calculateHMAC(signature[0], apiSecret);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    return null;
    }
}
    
private static String toHexString(byte[] bytes) {
Formatter formatter = new Formatter();
for (byte b : bytes) {
formatter.format("%02x", b);
}
return formatter.toString();
}

public static String calculateHMAC(String data, String key)
throws SignatureException, NoSuchAlgorithmException, InvalidKeyException
{
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "HmacSHA512");
Mac mac = Mac.getInstance("HmacSHA512");
mac.init(secretKeySpec);
return toHexString(mac.doFinal(data.getBytes()));
}
```

{% endtab %}
{% endtabs %}

### Verification of the Signature

#### **P**seudo Code

```
Function compareSignature(Argument responseData, Argument receivedSignature, Argument apiSecret)
	
	dataString: Stores the string genereated from request body
	signature: To store the generated signature
	REMOVE_ARRAY_KEY(responseData['signature'])
	
	For each KEY1 and VALUE1 in responseData, do
		If VALUE1 is Array Then
			For each KEY2 and VALUE2 in VALUE1, do
				APPEND VALUE2 to dataString
				APPEND '|' to dataString
			EndFor
		Else
			APPEND VALUE1 to dataString
			APPEND '|' to dataString
		EndIf
	EndFor
	
	APPEND '#' to dataString
	signature = HASH_HMAC_SHA_256(dataString, apiSecret)
	
	If signature IS NOT EQUAL TO receivedSignature Then
		Return False
	Else
		Return True
	EndIf
	
EndFunction
```

{% tabs %}
{% tab title="PHP" %}

```php
function compareSignature($transactionData, $receivedSignature, $apiSecret) {
$dataString = '';

// Unset signature from data
unset($transactionData['signature']);

foreach ($transactionData as $key => $value) {
if (is_array($value)) {
foreach ($value as $_key => $_value) {
    $dataString .= $_value;
    $dataString .= '|';
    }
} else {
$dataString .= $value;
$dataString .= '|';
}
}
$dataString .= '#';

// Creating signature
$signature = hash_hmac('sha512', $dataString, $apiSecret);

if(hash_equals($receivedSignature, $signature)) {
// Signature match
return true;
}

// Signature mismatch
return false;
}
```

{% endtab %}
{% endtabs %}


---

# 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.paykun.com/technical-guide/signature-generation-and-verification.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.
