gpt4 book ai didi

node.js - SHA-512 摘要的 NodeJS Base-64 编码

转载 作者:太空宇宙 更新时间:2023-11-04 01:28:53 25 4
gpt4 key购买 nike

我正在使用 Starling Bank Web hook 来调用我的 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。我是否正确理解/使用 crypto 和 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'];
});



关于node.js - SHA-512 摘要的 NodeJS Base-64 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56664705/

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