kristianheljas
7/2/2017 - 1:27 PM

PHP and ASP.NET HMAC-SHA256 signatures

PHP and ASP.NET HMAC-SHA256 signatures

// Returns either NameValueCollection of the signed data or NULL when request is not valid
private NameValueCollection getSignedRequestData()
{
	// Shared secret key between parties for signing requests
	String hmac_secret = "V3ryS3cureP@ssw0rd";

	// Get request parameters
	NameValueCollection requestData = Request.RequestType == "POST" ? Request.Form : Request.QueryString;

	// Remove signature_hash from query string for generating a signature
	String signedData = requestData.ToString();
	signedData = Regex.Replace(signedData, "&signature_hash=(.*?)$", "");

	// Calculate signature from requesr data and convert it to hex representation
	HMACSHA256 hmac = new HMACSHA256(Encoding.ASCII.GetBytes(hmac_secret));
	String calculatedSignature = BitConverter.ToString(hmac.ComputeHash(Encoding.ASCII.GetBytes(signedData))).Replace("-", "");

	if (requestData["signature_hash"] == calculatedSignature)
	{
		return requestData;
	}

	return null;
}
<?php
$hmac_secret = "V3ryS3cureP@ssw0rd";

$request_data = [
	'client_id' => 'abilitycoin',
	'payer_reference' => '46792556-e3c1-48d1-95c5-89ef61774bb2',
	'payer_email' => 'johndoe@example.com',
	'payer_first_name' => 'John',
	'payer_last_name' => 'Doe',
	'payment_reference' => 'd9b6601a-8cd1-455e-93e1-4e26b095c368',
	'payment_currency' => 'USD',
	'payment_amount' => 98.50,
	'return_url' => 'https://abilitycoin.com',
	'signature_algorithm' => 'HMAC-SHA256'
];

$request_data['signature_hash'] = strtoupper(hash_hmac('sha256', http_build_query($request_data), $hmac_secret));