Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

JWT Encryption With RSA

| Comments

This post is more like a quick note to self, which will quickly depict JWT encryption with RSA using openSSL.

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

Steps:

  • Create a RSA 2048 key:
1
$ openssl genrsa -des3 -out private.key 2048 # Private key.
1
$ openssl rsa -in private.key -outform PEM -pubout -out public.pem # Public key.
  • Sign the token:
1
2
3
4
5
6
7
8
9
10
11
// sign with default (HMAC SHA256)
var jwt = require('jsonwebtoken');

// sign with RSA SHA256
var cert = fs.readFileSync('private.key');  // get private key
var token = jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256'});

// sign asynchronously
jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256' }, function(err, token) {
  console.log(token);
});
  • Verify the token:
1
2
3
4
5
// verify a token asymmetric
var cert = fs.readFileSync('public.pem');  // get public key
jwt.verify(token, cert, function(err, decoded) {
  console.log(decoded.foo) // bar
});

Until next time, happy hacking!

Comments