我正在为GitHub编写一个Webhook,并在以下位置实现安全验证KOA.js:
function sign(tok, blob) {
var hmac;
hmac = crypto
.createHmac('sha1', tok)
.update(blob)
.digest('hex');
return 'sha1=' + hmac;
}
...
key = this.request.headers['x-hub-signature'];
blob = JSON.stringify(this.request.body);
if (!key || !blob) {
this.status = 400;
this.body = 'Bad Request';
}
lock = sign(settings.api_secret, blob);
if (lock !== key) {
console.log(symbols.warning, 'Unauthorized');
this.status = 403;
this.body = 'Unauthorized';
return;
}
...
Run Code Online (Sandbox Code Playgroud)
对于pull_requests和create事件,这工作正常,即使推送新分支也可以工作,但是对于推送提交事件,x-hub-signature来自有效负载的计算哈希值不匹配,因此它总是获得403未授权.
更新
我注意到,对于这种推送有效载荷,提交和head_commit被添加到有效载荷中.我已经尝试从正文中删除提交和head_commit但它没有用.
更新
有关更多信息,请查看这些示例有效负载.我还为测试回购和令牌信息添加了url:https://gist.github.com/marcoslhc/ec581f1a5ccdd80f8b33
我正在与Ruby,PHP和NodeJS并行进行以下代码的比较,使用该crypto模块在NodeJS中获得不正确的响应.
PHP
hash_hmac('sha256', 'text', 'á');
Run Code Online (Sandbox Code Playgroud)
红宝石
OpenSSL::HMAC.hexdigest('sha256', 'á', 'text')
Run Code Online (Sandbox Code Playgroud)
的NodeJS
var signer = crypto.createHmac('sha256', 'á');
var expected = signer.update("text").digest('hex');
Run Code Online (Sandbox Code Playgroud)
Ruby和PHP都返回34b3ba4ea7e8ff214f2f36b31c6a6d88cfbf542e0ae3b98ba6c0203330c9f55b,而NodeJS返回7dc85acba66d21e4394be4f8ead2a327c9f1adc64a99c710c98f60c425bd7411.我注意到,如果我utf8_encode('á')在PHP中尝试,它实际上给了我Node期望的结果.
我正在从文件中加载Node中的重音文本,如下所示:
JSON.parse(fs.readFileSync('keys.js', 'utf8'));
Run Code Online (Sandbox Code Playgroud)
我将如何在Node中更改我的代码以获得PHP和Ruby都存在的结果哈希?
谢谢!