如何将 Buffer.from() 与 crypto.timingSafeEqual() 一起使用?

San*_*ing 6 javascript node.js ecmascript-6

由于某种原因我得到

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined
Run Code Online (Sandbox Code Playgroud)

从两个参数到crypto.timingSafeEqual(a, b).

我也尝试过

const a = Buffer.from(signature, 'utf8').toString('base64');
const b = Buffer.from(expectedSignature, 'utf8').toString('base64');
Run Code Online (Sandbox Code Playgroud)

我得到同样的错误。

问题

谁能弄清楚为什么参数不是缓冲区?

const express = require("express");
const bodyParser = require("body-parser");
const crypto = require('crypto');
const secret = "x";

const app = express();
const PORT = 8080;

app.use(bodyParser.json());

function isSigOk(request, secret) {
    // calculate the signature
    const expectedSignature = "sha256=" +
        crypto.createHmac("sha256", secret)
            .update(JSON.stringify(request.body))
            .digest("hex");

    // compare the signature against the one in the request
    const signature = request.headers["X-Hub-Signature-256"];
    const a = Buffer.from(signature);
    const b = Buffer.from(expectedSignature);
    return crypto.timingSafeEqual(a, b);
};

app.post("/", (req, res) => {
  if (isSigOk(req, secret)) {
    // Do stuff here
  } else {
    console.log('Error: Signatures does not match. Return res.status(401)');
  };
  res.status(200).end();
});

// Start express on the defined port
app.listen(PORT, () => console.log(`Github wekhook listening on port ${PORT}`));
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 9

我看到两个问题:

  1. 第一个也是主要的一个是isSigOk假设标头一个值"X-Hub-Signature-256"

    const signature = request.headers["X-Hub-Signature-256"];
    const a = Buffer.from(signature);
    
    Run Code Online (Sandbox Code Playgroud)

    如果是因为标头不存在,该Buffer.from调用将引发您引用的错误。在这种情况下,您可能希望返回(并且可能通过稍微重新排序来跳过计算预期签名的开销),请参阅注释和相关行:signatureundefinedfalse***

    function isSigOk(request, secret) {
        // *** get the signature on this message, if any
        const signature = request.headers["X-Hub-Signature-256"];
        if (!signature) {
            // *** none
            return false;
        }
        // calculate the signature
        const expectedSignature = "sha256=" +
            crypto.createHmac("sha256", secret)
                .update(JSON.stringify(request.body))
                .digest("hex");
    
        // compare the signature against the one in the request
        const a = Buffer.from(signature);
        const b = Buffer.from(expectedSignature);
        return crypto.timingSafeEqual(a, b);
    };
    
    Run Code Online (Sandbox Code Playgroud)
  2. 资本化问题。根据Node.js 文档(Express 的Request对象继承自 Node.js 的IncomingMessage),headers的名称是小写的。request.headers["X-Hub-Signature-256"]应该如此request.headers["x-hub-signature-256"]。(在评论中,您说您正在获取一个值,但评论全部使用小写,而代码使用混合大小写。)所以:

    function isSigOk(request, secret) {
        // *** get the signature on this message, if any
        const signature = request.headers["x-hub-signature-256"]; // *** Lowercase
        if (!signature) {
            // *** none
            return false;
        }
        // calculate the signature
        const expectedSignature = "sha256=" +
            crypto.createHmac("sha256", secret)
                .update(JSON.stringify(request.body))
                .digest("hex");
    
        // compare the signature against the one in the request
        const a = Buffer.from(signature);
        const b = Buffer.from(expectedSignature);
        return a.length === b.length && crypto.timingSafeEqual(a, b);
    };
    
    Run Code Online (Sandbox Code Playgroud)

    请注意a.length === b.length &&那部分。timingSafeEqual如果缓冲区长度不同,则会抛出错误,但我们希望在这种情况下返回 false。

  • 最好比较返回中的 byteLength,如 `return Buffer.byteLength(a) === Buffer.byteLength(b) && crypto.timingSafeEqual(a, b);` ,否则如果两个 buff 有,它可能会在 nodejs 中抛出 `RangeError`长度不同。 (3认同)