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 to generate or validate the signature.

Generation of Signature

Pseudo 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
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;
}

Verification of the Signature

Pseudo 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
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;
}

Last updated