php PHP和ASP.NET HMAC-SHA256签名

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php PHP和ASP.NET HMAC-SHA256签名相关的知识,希望对你有一定的参考价值。

// 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));

以上是关于php PHP和ASP.NET HMAC-SHA256签名的主要内容,如果未能解决你的问题,请参考以下文章

ASP、PHP、JSP、ASP.net、CGI等,哪种比较好学,容易入门?

PHP 中的 ASP.Net API 使用

服务器网页HTTP状态查询:X-Powered-By: ASP.NET,PHP/5.2.5

asp/php/asp.net 上传附件大小修改怎么操作?

什么是 ASP.NET / PHP 的主流 Java 替代品

PHP API接口签名验证