---
title: "JWT Encryption with RSA"
description: "Quick guide to JWT encryption with RSA using openSSL and Node.js. Practical notes and code examples on JWT Encryption with."
url: "https://h3manth.com/scribe/jwt-encryption-with-rsa/"
canonical_url: "https://h3manth.com/scribe/jwt-encryption-with-rsa/"
markdown_url: "https://h3manth.com/scribe/blog/jwt-encryption-with-rsa.md"
publishDate: "2017-08-22T00:00:00.000Z"
author: "Hemanth HM"
category: "node"
tags: ["node","javascript","security","jwt"]
word_count: 143
reading_time_minutes: 1
x_markdown_tokens: 377
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# JWT Encryption with RSA

> Quick guide to JWT encryption with RSA using openSSL and Node.js. Practical notes and code examples on JWT Encryption with.

This post depicts [JWT](https://jwt.io/) encryption with [RSA](https://en.wikipedia.org/wiki/RSA_(cryptosystem)) using [openSSL](https://www.openssl.org/docs/faq.html).

I prefer using [jsonwebtokens](https://npm.im/jsonwebtokens) which was developed against `draft-ietf-oauth-json-web-token-08`. It makes use of [node-jws](https://npm.im/node-jws).

## Steps

### 1. Create RSA 2048 Key

```bash
# 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!
