Create JWT Token and Sign with RSA Private Key

Create JWT Token and Sign with RSA Private Key

This tutorial guides you on how to create JWT token and sign with RSA private key. JWT (JSON Web Token) is an encoded representation of a JSON object. JWTs are used in authentication/ authorization mechanisms.

Create JWT Token and Sign with RSA Private Key

As mentioned JWT’s are encoded representation of a JSON object. The JSON object consists of one or more name:value pairs, where names are strings and values are JSON values.

{
  "issuer": "SneppetsMobileApp",
  "subject": "[email protected]",
  "server": "sneppets.com",
  "device_id": "sneppets_device_100",
  "app_version": "2.1.3",
  "os": "ios",
  "user_type": "student",
  "client_id": "SneppetsMobileApp",
  "pin": "1234"
}

We are going to use the following Java library to create JWT token and sign with RSA private key.

https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt (JSON Web Token)

I also added the following jar files in the build path along with jjwt jar. Make sure that you download from maven repository and configure them in the build path.

  • jackson-core-2.11.2.jar
  • jackson-databind-2.11.2.jar
  • jackson-annotations-2.11.2.jar
  • jaxb-api-2.3.1.jar
  • jjwt-0.9.1 ( JSON Web Token)

Note, you need to convert the “private.pem” private key which is in PKCS#1 format to PKCS#8 format. Therefore Java code can read PKCS#8 key format. Otherwise you will get Java Exception “java.security.spec.InvalidKeySpecException”.

You need to run the following command, which will output private key in DER format which Java code can read with the help of  “PKCS8EncodedKeySpec” interface.

> openssl pkcs8 -topk8 -inform PEM -outform DER -in private.pem -out private.der -nocrypt

I had converted the private.pem to private.der and going to use them in the following program to generate tokens.

Also See: How to read .pem file to get public and private keys ?

Now, let’s see how to generate tokens and sign with RSA private key.

Example: Create JWT Token with Java Library

The following example demonstrates the JWT token generation and signing it with RSA private key.

CreateJWTAndSignExample.java

package com.sneppets.util;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;


public class CreateJWTAndSignExample {
	
	public static void main (String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
		
		System.out.println("Generating JWT snd Signing with Private Key...........");		
		RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey("private.der");		
		String jwtToken = createJWTAndSign("SneppetsMobileApp", "[email protected]", "sneppets.com", "sneppets_device_100", "2.1.3", "ios", "student", "SneppetsMobileApp", "1234", privateKey);
		System.out.println("JWT Token:");		
		System.out.println(jwtToken);      
		
	}

	private static String createJWTAndSign(String issuer, String subject, String server, String deviceid, String appversion,
			String os, String userType, String clientid, String pin, RSAPrivateKey privateKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
		
		
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS256;
		
		JwtBuilder builder = Jwts.builder().claim("issuer", issuer)
										.claim("subject", subject)
										.claim("server", server)
										.claim("device_id", deviceid)
										.claim("app_version", appversion)
										.claim("os", os)
										.claim("user_type", userType)
										.claim("client_id", clientid)
										.claim("pin", pin)
										.signWith(signatureAlgorithm, privateKey);
		
		return builder.compact();
		
	}

	private static RSAPrivateKey getPrivateKey(String filename) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
		
		File file = new File(filename);
		FileInputStream fis = new FileInputStream(file);
        DataInputStream dis = new DataInputStream(fis);
        
        byte[] keyBytes = new byte[(int) file.length()];
        dis.readFully(keyBytes);
        dis.close();
        
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(spec);
        
        return privateKey;
	}

}

Ouput: JWT Token Generated and Signed

Generating JWT snd Signing with Private Key...........
JWT Token:
eyJhbGciOiJSUzI1NiJ9.eyJpc3N1ZXIiOiJT
bmVwcGV0c01vYmlsZUFwcCIsInN1YmplY3QiO
iJhZG1pbkBzbmVwcGV0cy5jb20iLCJzZXJ2ZXI
iOiJzbmVwcGV0cy5jb20iLCJkZXZpY2VfaWQiO
iJzbmVwcGV0c19kZXZpY2VfMTAwIiwiYXBwX3Z
lcnNpb24iOiIyLjEuMyIsIm9zIjoiaW9zIiwid
XNlcl90eXBlIjoic3R1ZGVudCIsImNsaWVudF9
pZCI6IlNuZXBwZXRzTW9iaWxlQXBwIiwicGluI
joiMTIzNCJ9.VKu0u9oXptPA172fI_UNbgJr0e
RgyqaCIccx_tluwvjtoeoPiCafHsvbbvCYycWY
FlSxxx3rKswAJlhJtrxhZf5Bxzngk6Q2IQMV_B
PjCMfrf9ZpFBA6zvU45hOTXiwzUBu-CfOaRiWg
ZoiJuEB_gONqJItrRItDtGxrY2v8fAt_DKnL1t
rSoUIxI7J2VgTBzEF7lQL0irhOAyEtDTf_hOjd
WBJGx-0nVqPw5MN_iJGTYAhByrAC28Pb4UsrPn
5l_lJOMBmXHZDUTWzj8k-e5a42gUuLCm11gd_9
UrD4FAg4SbDE_fcfGCkzLJyvKFpadfNKs234e8
NxkPVIFaaIRA

Decode and Verify – JWT Token Java Library

You can implement/add the following method in your CreateJWTAndSignExample.java class to decode and verify the JWT token signed with private key.

private static void decodeAndVerify(String jwtToken, RSAPrivateKey privateKey) {

     Claims claims = Jwts.parser().setSigningKey(privateKey)
                                  .parseClaimsJws(jwtToken).getBody();			   
     System.out.println("issuer: " + claims.get("issuer"));
     System.out.println("subject: " + claims.get("subject"));
     System.out.println("server: " + claims.get("server"));
     System.out.println("device_id: " + claims.get("device_id"));
     System.out.println("app_version: " + claims.get("app_version"));
     System.out.println("os: " + claims.get("os"));
     System.out.println("user_type: " + claims.get("user_type"));
     System.out.println("client_id: " + claims.get("client_id"));
     System.out.println("pin: " + claims.get("pin"));
		
}

Just, modify your main() method like below.

public static void main (String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
		
     System.out.println("Generating JWT snd Signing with Private Key...........");		
     RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey("private.der");		
     String jwtToken = createJWTAndSign("SneppetsMobileApp", "[email protected]", "sneppets.com", "sneppets_device_100", "2.1.3", "ios", "student", "SneppetsMobileApp", "1234", privateKey);
     System.out.println("JWT Token:");		
     System.out.println(jwtToken);
      
     //decode and verify JWT token
     System.out.println();
     System.out.println("Decoding and verifying jwt token...........");	
     decodeAndVerify(jwtToken, privateKey);
}

Output

Then running CreateJWTAndSignExample.java program, you should see the following output.

Generating JWT snd Signing with Private Key...........
JWT Token:
eyJhbGciOiJSUzI1NiJ9.eyJpc3N1ZXIiOiJTbmVwcGV0c01vYmlsZUFwcCIsInN1YmplY3QiOiJhZG1pbkBzbmVwcGV0cy5jb20iLCJzZXJ2ZXIiOiJzbmVwcGV0cy5jb20iLCJkZXZpY2VfaWQiOiJzbmVwcGV0c19kZXZpY2VfMTAwIiwiYXBwX3ZlcnNpb24iOiIyLjEuMyIsIm9zIjoiaW9zIiwidXNlcl90eXBlIjoic3R1ZGVudCIsImNsaWVudF9pZCI6IlNuZXBwZXRzTW9iaWxlQXBwIiwicGluIjoiMTIzNCJ9.VKu0u9oXptPA172fI_UNbgJr0eRgyqaCIccx_tluwvjtoeoPiCafHsvbbvCYycWYFlSxxx3rKswAJlhJtrxhZf5Bxzngk6Q2IQMV_BPjCMfrf9ZpFBA6zvU45hOTXiwzUBu-CfOaRiWgZoiJuEB_gONqJItrRItDtGxrY2v8fAt_DKnL1trSoUIxI7J2VgTBzEF7lQL0irhOAyEtDTf_hOjdWBJGx-0nVqPw5MN_iJGTYAhByrAC28Pb4UsrPn5l_lJOMBmXHZDUTWzj8k-e5a42gUuLCm11gd_9UrD4FAg4SbDE_fcfGCkzLJyvKFpadfNKs234e8NxkPVIFaaIRA

Decoding and verifying jwt token...........
issuer: SneppetsMobileApp
subject: [email protected]
server: sneppets.com
device_id: sneppets_device_100
app_version: 2.1.3
os: ios
user_type: student
client_id: SneppetsMobileApp
pin: 1234

You could also verify the signature via jwt.io website as shown below. Just copy the JWT token generated and paste it in the encoded text box. You also need to enter the public key to verify the signature. As a result you can see the decoded data (header & payload) and signature verified status.

Create JWT Token and Sign with RSA Private Key

That’s it. Hope this tutorial helped you in creating JWT tokens and verifying them in a easy way. Hope it helped 🙂

Also See:

References:

guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Raul
Raul
3 months ago

Thanks for your work!