gpt4 book ai didi

javascript - 使用 Node.js、Express 和 Trialpay 进行 HMAC MD5 验证

转载 作者:数据小太阳 更新时间:2023-10-29 04:48:28 28 4
gpt4 key购买 nike

我正在尝试使用 Node.js 和 Express 验证从 TrialPay 发送的消息。 TrialPay 使用 HMAC-MD5 哈希对请求进行签名,并提供 these instructions关于验证。

这是我的代码:

app.post('/trialpay', function(req, res) {

var key = "[MY MERCHANT KEY]";
var hash = req.header("TrialPay-HMAC-MD5");
var data = req.body.toString();

var crypted = require("crypto").createHmac("md5", key)
.update(data)
.digest("hex");

if (hash == crypted) {
res.writeHead(200, {"Content-Type": "plain/text"});
res.end("Success!");
} else {
throw new Error("Invalid TrialPay Hash");
}
});

这显然不起作用(哈希不匹配)。

免责声明:我对 Node.js 非常陌生,一开始几乎没有 Javascript 经验。

更新

我没有意识到该链接已受到保护。

TrialPay uses your Notification-Key (set in your account information) as the secret key to sign the HMAC. For GET requests the query string that follows the question mark (in the URL) is signed. For POST requests the entire POST body is signed.

以下是 TrialPay 如何指导您在 Google App Engine (Python) 中进行验证的示例:

class MyHandler(webapp.RequestHandler):
def post(self):
key = '[YOUR MERCHANT KEY]'
tphash = self.request.headers['TrialPay-HMAC-MD5']
if hmacmd5(key,self.request.body) != tphash:
logging.info('invalid trialpay hash')
return

更新 2

req.body 打印如下:

{ 
oid: 'sample-order-id',
sid: 'customer-sid',
order_date: '04/24/2012',
timestamp: '04/24/2012 16:28:46',
first_name: 'customer-firstname',
last_name: 'customer-lastname',
email: 'customer@trialpay.com',
revenue: '10.00',
zip_code: '94041',
country: 'US'
}

最佳答案

这应该可以解决问题:

var crypto = require('crypto');

function calculateSignature(key) {
return function(req, res, next) {
var hash = req.header("TrialPay-HMAC-MD5"),
hmac = crypto.createHmac("md5", key);

req.on("data", function(data) {
hmac.update(data);
});

req.on("end", function() {
var crypted = hmac.digest("hex");

if(crypto.timingSafeEqual(
Buffer.from(crypted),
Buffer.from(hash.padEnd(crypted.length))
)) {
// Valid request
return res.send("Success!", { "Content-Type": "text/plain" });
} else {
// Invalid request
return res.send("Invalid TrialPay hash", { "Content-Type": "text/plain" }, 403);
}
});

req.on("error", function(err) {
return next(err);
});
}
}

app.post("/trialpay", calculateSignature("[MY MERCHANT KEY]"));

关于javascript - 使用 Node.js、Express 和 Trialpay 进行 HMAC MD5 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10305067/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com