How to generate RSA SHA256 signature by Javascript

8,004 views
Skip to first unread message

Nalini Shrma

unread,
Jul 13, 2017, 4:37:53 PM7/13/17
to nodejs
Hi,

I want to generate RSA SHA256 token based on jwt.io by javascript. Is there any source code or anything or available. 


Regards

Nalini Shrma

unread,
Jul 14, 2017, 2:08:14 PM7/14/17
to nodejs
Hi,

I want to generate RSA SHA256 token based on jwt.io by javascript. Is there any source code or anything or available.

Regards,  

Ben Turner

unread,
Jul 15, 2017, 1:52:55 AM7/15/17
to nodejs
Why not just use the jwt.io library https://jwt.io/#libraries-io

dorian_...@wrdsb.ca

unread,
Sep 14, 2017, 5:55:10 PM9/14/17
to nodejs
Did you have any luck accomplishing this? I'm trying to do something similar/same, I want to get an oauth2 access token for a google service account so that I can then make calls to the gmail api. However after forming the JWT to post to the oauth endpoint all I get is Invalid signature. I have a stackoverflow question up right now that goes into more detail than this post with some of my code. You can see it here: https://stackoverflow.com/questions/46221972/nodejs-post-request-to-get-oauth2-token-for-a-service-account

Did you get it to work?

Jaret Flores

unread,
Sep 15, 2017, 5:13:12 PM9/15/17
to nodejs
So certainly there are libraries for this as @Nalini points out.

Here is some Node.js sample code that may present some ideas you can use.  Warning: I have not run the code nor do I advocate that it replicates JWT, but it's looks like something I would start with if I were to try to implement it.

const crypto = require('crypto');

const header = { alg: 'HS256', typ: 'JWT' },
    data = { a: 1 b: 2 },
    secret = 'secret';

assert(isValidJwt(makeJwt(header, data, secret), secret));

function makeJwt (header, data, secret) {
   
const base64Header = objToBase64(header);
        base64Data
= objToBase64(data),
        base64Signature
= jwtSignature(base64Header, base64Data, secret);

   
return base64Header + '.' + base64Data + '.' base64Signature;
}

function isValidJwt (jwt, secret) {
   
const [base64Header, base64Data, base64Signature] = jwt.split('.');

   
return base64Signature === jwtSignature(base64Header, base64Data, secret);
}

function jwtSignature (base64Header, base64Data, secret) {
   
return crypto
       
.createHmac('sha256', secret)
       
.update(base64Header + '.' + base64Data)
       
.digest('base64');
}

function objToBase64 (obj) {
   
return Buffer.from(JSON.stringify(obj), 'utf8').toString('base64');
}

Nagesh Kumar

unread,
Sep 18, 2017, 9:40:02 AM9/18/17
to nodejs
You seem to have RSA and DSA confused. However, if you want to sign using RSA-sha256, then use the EVP interface for signing. You can initialize with the EVP_SignInit_ex() method with EVP_sha256() for the type argument.

thank you
Reply all
Reply to author
Forward
0 new messages