Search code examples
node.jscryptojs

NodeJS Base-64 encoding of the SHA-512 digest


I am using the Starling Bank web hooks to call my API. They state the following:

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.

My code that I ended up with is below. Having tried different ways, I can not seem to get the same Base-64 of the SHA-512 as what is in the header. Am I understanding/using the crypto and bodyParser library correctly?

// 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();
}

My app has the following code

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);

Solution

  • The problem is that express and bodyParser are messing with the rawBody.

    This should work:

    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'];
    });