Last active
July 2, 2017 15:51
-
-
Save kristianheljas/303f699e7b53507ff07b2e35c2bf65dd to your computer and use it in GitHub Desktop.
PHP and ASP.NET HMAC-SHA256 signatures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment