Hemanth's Scribes

node

JWT Encryption with RSA

Author Photo

Hemanth HM

Thumbnail

This post depicts JWT encryption with RSA using openSSL.

I prefer using jsonwebtokens which was developed against draft-ietf-oauth-json-web-token-08. It makes use of node-jws.

Steps

1. Create RSA 2048 Key

# Generate private key
$ openssl genrsa -des3 -out private.key 2048

# Generate public key
$ openssl rsa -in private.key -outform PEM -pubout -out public.pem

### 2. Sign the Token
javascript
var jwt = require('jsonwebtoken');
var fs = require('fs');

// Get private key
var cert = fs.readFileSync('private.key');

// Sign with RSA SHA256
var token = jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256' });

// Or sign asynchronously
jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256' }, function(err, token) {
  console.log(token);
});

### 3. Verify the Token
javascript
// Get public key
var cert = fs.readFileSync('public.pem');

jwt.verify(token, cert, function(err, decoded) {
  console.log(decoded.foo) // bar
});

Until next time, happy hacking!

#node#javascript#security#jwt
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.