使用Node.js,Express和Trialpay进行HMAC MD5验证

时间:2012-04-24 19:52:48

标签: javascript node.js cryptography express

我正在尝试使用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使用您的通知密钥(在您的帐户信息中设置)   作为签署HMAC的秘密密钥。对于GET请求查询字符串   签名后面的问号(在URL中)。对于POST   请求整个POST正文已签名。

以下是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' 
}

2 个答案:

答案 0 :(得分:4)

这应该可以解决问题:

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(crypted === hash) {
                // 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]"));

答案 1 :(得分:-1)

对于Parse Cloud Code :(我已测试过) 重点是express.bodyParser将解析用于散列的url编码字符串。

var parseExpressRawBody = require('parse-express-raw-body');
var queryString = require('querystring');
app.post('/trialpay',parseExpressRawBody(),function(req, res) {
var hmac, calculatedSignature,payloadStr=req.body.toString();
hmac = crypto.createHmac('md5', TrialPayMerchentKey);
hmac.update(payloadStr);
calculatedSignature = hmac.digest('hex');

if (req.headers['trialpay-hmac-md5'] === calculatedSignature) {
   ~~~~~~
相关问题