Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Generate JWT Signature (HS256) in Node.js

How to create JWT Signature using HS256 algorithm in Node.js?

I’ll be using it to generate digital signature required for every request in here BNI API

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To generate JWT Signature in HS256 to be use for digital signature in BNI API you must convert payload to base64URL first, try this code

// convert to JWT base64URL
const escape = (string) => {
  return string.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
};

const generateSignature = (body, secret) => {
  // generate JWT header
  const header = escape(Buffer.from('{"alg":"HS256","typ":"JWT"}').toString('base64'));

  // generate JWT payload
  const payload = escape(Buffer.from(JSON.stringify(body)).toString('base64'));

  // generate JWT signature
  const jwtSignature = crypto.createHmac('SHA256', secret).update(`${header}.${payload}`).digest('base64');

  // return generated JWT token
  return escape(`${header}.${payload}.${jwtSignature}`);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading