Sign JSON Web Tokens (JWT) with Java using PKCS11 library
This article covers how to sign a JSON Web Token (JWT) using Java code. For your convenience, we have provided a template that only requires you to specify the values of your JWT token. Alternatively, you can sign JWT using jwt.io.
Before you begin
You will need the following information to complete JWT signing:
Algorithm type
Payload claims
Client certificate file path
Client certificate password
Host: The DigiCert ONE® environment you want to connect to.
Tableau 1. Host optionsCountry
Host type
SM_HOST value
United States of America (USA)
Demo
https://clientauth.demo.one.digicert.com
Production
https://clientauth.one.digicert.com
Switzerland (CH)
Demo
https://clientauth.demo.one.ch.digicert.com
Production
https://clientauth.one.ch.digicert.com
Japan (JP)
Demo
https://clientauth.demo.one.digicert.co.jp
Production
https://clientauth.one.digicert.co.jp
Netherlands (NL)
Demo
https://clientauth.demo.one.nl.digicert.com
Production
https://clientauth.one.nl.digicert.com
Let's begin
Download the jwtsigning.zip file.
Right click on the file and select Extract all…
Open JWTsigning > src > main > java.
Open JwtCreateHeader.java in a plain text editor or Integrated Development Environment (IDE).
Find and specify your preferred algorithm in:
headerMap.put("alg", "< insert algorithm>");
Save the JwtCreateHeader.java file.
Open JwtCreatePayload.java in a plain text editor or Integrated Development Environment (IDE).
Find and add your required payload claims by editing:
payloadMap.put("<insert claim>", "<insert value>");
Save the JwtCreatePayload.java file.
Sign
Open Command Prompt.
Set the environment variables to connect to DigiCert® Software Trust Manager :
SM_HOST:<Prod host or demo host> SM_API_KEY:<API key> SM_CLIENT_CERT_PASSWORD:<client certificate password> SM_CLIENT_CERT_FILE:<client certificate secure file path>
Enter the file path to the JWTsigning folder:
C:\Users\Name\Downloads\JWTsigning
Run:
mvnw clean install
Edit and run the following command:
java -jar target/JWTsigning-1.0-SNAPSHOT <keypair alias> <algorithm>
FAQ
What is the header?
The cryptographic operations in the header define whether the JWT is signed or unsigned, and also whether it is encrypted and if so by what algorithm.
Example
headerMap.put("alg", "RS256");
What is the payload?
The payload generally contains user information. You are not required to add any claims to a payload, but you can add as many as you like.
Examples
payloadMap.put("sub", "1234567890"); payloadMap.put("name", "John Doe"); payloadMap.put("admin", "true"); payloadMap.put("iat", 1516239022);
What is the main difference between Base64 and Base64URL?
Base64 contains the characters +, /, and =, which have a reserved meaning in some filesystem names and URLs. Base64URL solves this by replacing + with - and / with _. The trailing padding character = can be eliminated when not required.