SHA-512 摘要的 NodeJS Base-64 编码

NodeJS Base-64 encoding of the SHA-512 digest

我正在使用 Starling Bank 网络挂钩来调用我的 API。他们声明如下:

The signature is placed in the header of the request using X-Hook-Signature and consists of Base-64 encoding of the SHA-512 digest of the secret + JSON payload.

我最终得到的代码如下。尝试了不同的方法后,我似乎无法获得与 header 中相同的 SHA-512 Base-64。我 understanding/using 加密和 bodyParser 库是否正确?

// middleware.js
const functions = require('firebase-functions');
import * as crypto from 'crypto';

export const auth = (req, res, next) => {
    let hash = crypto.createHash('sha512');
    hash.update(config.starling.key + req.rawBody));
    req.hasha = hash.digest('base64');

    // req.hasha is different from req.header('X-Hook-Signature')

    next();
}

我的应用有以下代码

import * as functions from 'firebase-functions';
import * as express from 'express';
import * as cors from 'cors';
import * as middleware from './middleware';
import bodyParser = require('body-parser');

const app = express();
app.use(cors({ origin: true }));
app.use(bodyParser.json());
app.use(middleware.auth);

// Endpoints removed for brevity

export const hooks = functions.https.onRequest(app);

问题是 express 和 bodyParser 弄乱了 rawBody。

这应该有效:

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

app.use(bodyParser.json({
  verify: (req, res, buf) => {
    req.rawBody = buf
  }
}));

app.post('/starling',async (request,response)=>{

  const secret = 'abcd-efgh-12f3-asd34-casd-whatever';

  let hash = crypto.createHash('sha512');

  hash.update(secret+request.rawBody);

  const sigCheck = hash.digest('base64');
  
  const valid = sigCheck==request.headers['x-hook-signature'];
});