JSON Web Token (JWT) with RSA encryption (2024)

RSA is a popular algorithmfor asymmetric (public key) encryption that was established more than 40 yearsago. Encrypting a JWT for a given recipient requires their public RSA key. Thedecryption takes place with the corresponding private RSA key, which therecipient must keep secret at alltimes.

To create an RSA encrypter with Nimbus JOSE+JWT for a given publickey:

JWEEncrypter encrypter = new RSAEncrypter(rsaPublicKey);

To create an RSAdecrypter:

JWEDecrypter decrypter = new RSADecrypter(rsaPrivateKey);

An absolutely essential security aspect in public key encryption is ensuringthe data is encrypted for the intended recipient and not some other party,which will compromise the data's confidentiality. One solution is public keyinfrastructure, suchas based on the PKIX / X.509 standard(used for SSL/TLS on the Internet and in otherplaces).

The actual public key encryption is a two step process, to work around an RSAlimitation that makes it unfeasible to encrypt data that is more than a fewhundred bytes long. The library takes care of this internally, so you only needto supply the public key, the RSA algorithm name (alg) and the contentencryption algorithm name (enc) in order to encrypt a piece of data, such asthe claims for aJWT.

If you are curious know what those two encryption stepsare:

  1. A single use secret AES or ChaCha20 key (called Content Encryption Key, orCEK) is generated to perform symmetrical encryption on the JWT payload.These symmetric ciphers are super efficient and can process plain text of(almost) arbitrary size. The type and length of the CEK to be generated isdetermined by the JWE "enc" header parameter. For example, A128GCM willcause a 128-bit AES CEK to begenerated.
  2. The generated CEK, which fits the RSA size limitation, is then encryptedwith RSA according to the JWE "alg" header parameter, and gets includedas part of theJWT.

There are two standard RSA algorithm types for JSON WebEncryption (JWE), identified bythe JWE "alg" headerparameter:

JWE algDescription
The CEK is encrypted with RSAES with Optimal Asymmetric Encryption Padding (OAEP).Use RSA-OAEP-256or another SHA-2 based RSA algorithm. Don't useRSA-OAEPbecause it's SHA-1 hashing is considered weak for today's applications.
The CEK is encrypted with RSAES-PKCS1-v1_5. Use of this algorithm isgenerally not recommended due to asecurityvulnerability. Provided for backward compatibility with older software.

You can combine a JWE "alg" with any of the following contentencryption algorithms,identified by the JWE "enc" headerparameter:

JWE algDescription
AES/CBC/HMAC/SHA-2 authenticated encryption
AES/GCM
eXtended-nonce ChaCha / Poly1305

The following example demonstrates RSA-OAEP-256 with A128GCM encryptionof a JWT, where the recipient'sjava.security.interfaces.RSAPublicKeyis used to encrypt the JWT. The recipient can then decrypt the JWT with itsjava.security.interfaces.RSAPrivateKey.

Check out /src/test/java/com/nimbusds/jwt/EncryptedJWTTest.java to see the
completecode.

import java.util.*;import java.security.interfaces.*;import javax.crypto.*;import com.nimbusds.jose.*;import com.nimbusds.jose.crypto.*;import com.nimbusds.jwt.*;// Compose the JWT claims setDate now = new Date();JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder() .issuer("https://openid.net") .subject("alice") .audience(Arrays.asList("https://app-one.com", "https://app-two.com")) .expirationTime(new Date(now.getTime() + 1000*60*10)) // expires in 10 minutes .notBeforeTime(now) .issueTime(now) .jwtID(UUID.randomUUID().toString()) .build();System.out.println(jwtClaims.toJSONObject());// Produces// {// "iss" : "https://openid.net",// "sub" : "alice",// "aud" : [ "https://app-one.com" , "https://app-two.com" ],// "exp" : 1364293137871,// "nbf" : 1364292537871,// "iat" : 1364292537871,// "jti" : "165a7bab-de06-4695-a2dd-9d8d6b40e443"// }// Request JWT encrypted with RSA-OAEP-256 and 128-bit AES/GCMJWEHeader header = new JWEHeader( JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A128GCM);// Create the encrypted JWT objectEncryptedJWT jwt = new EncryptedJWT(header, jwtClaims);// Create an encrypter with the specified public RSA keyRSAEncrypter encrypter = new RSAEncrypter(publicKey);// Do the actual encryptionjwt.encrypt(encrypter);// Serialise to JWT compact formString jwtString = jwt.serialize();System.out.println(jwtString);// Produces//// eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkExMjhHQ00ifQ.K52jFwAQJH-// DxMhtaq7sg5tMuot_mT5dm1DR_01wj6ZUQQhJFO02vPI44W5nDjC5C_v4p// W1UiJa3cwb5y2Rd9kSvb0ZxAqGX9c4Z4zouRU57729ML3V05UArUhck9Zv// ssfkDW1VclingL8Lfa*gRUs2z95UkwhiZyaKpmrgqpKX8azQFGNLBvEjXnx// -xoDFZIYwHOno290HOpig3aUsDxhsioweiXbeLXxLeRsivaLwUWRUZfHRC// _HGAo8KSF4gQZmeJtRgai5mz6qgbVkg7jPQyZFtM5_ul0UKHE2y0AtWm8I// zDE_rbAV14OCRZJ6n38X5urVFFE5sdphdGsNlA.gjI_RIFWZXJwaO9R.oa// E5a-z0N1MW9FBkhKeKeFa5e7hxVXOuANZsNmBYYT8G_xlXkMD0nz4fIaGt// uWd3t9Xp-kufvvfD-xOnAs2SBX_Y1kYGPto4mibBjIrXQEjDsKyKwndxzr// utN9csmFwqWhx1sLHMpJkgsnfLTi9yWBPKH5Krx23IhoDGoSfqOquuhxn0// y0WkuqH1R3z-fluUs6sxx9qx6NFVS1NRQ-LVn9sWT5yx8m9AQ_ng8MBWz2// BfBTV0tjliV74ogNDikNXTAkD9rsWFV0IX4IpA.sOLijuVySaKI-FYUaBy// wpg// Parsejwt = EncryptedJWT.parse(jwtString);// Create a decrypter with the specified private RSA keyRSADecrypter decrypter = new RSADecrypter(privateKey);// Decryptjwt.decrypt(decrypter);// Retrieve JWT claimsSystem.out.println(jwt.getJWTClaimsSet().getIssuer());;System.out.println(jwt.getJWTClaimsSet().getSubject());System.out.println(jwt.getJWTClaimsSet().getAudience().size());System.out.println(jwt.getJWTClaimsSet().getExpirationTime());System.out.println(jwt.getJWTClaimsSet().getNotBeforeTime());System.out.println(jwt.getJWTClaimsSet().getIssueTime());System.out.println(jwt.getJWTClaimsSet().getJWTID());
JSON Web Token (JWT) with RSA encryption (2024)

FAQs

JSON Web Token (JWT) with RSA encryption? ›

RSA is a popular algorithm for asymmetric (public key) encryption that was established more than 40 years ago. Encrypting a JWT for a given recipient requires their public RSA key.

Does JWT use RSA? ›

This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA. Although JWTs can be encrypted to also provide secrecy between parties, we will focus on signed tokens.

Can JSON Web tokens be encrypted? ›

Security of JWTs

The information contained within the JSON object can be verified and trusted because it is digitally signed. Although JWTs can also be encrypted to provide secrecy between parties, Auth0-issued JWTs are JSON Web Signatures (JWS), meaning they are signed rather than encrypted.

What is the best encryption for JWT? ›

The option with the best security and performance is EdDSA, though ES256 (The Elliptic Curve Digital Signature Algorithm (ECDSA) using P-256 and SHA-256) is also a good choice.

How to generate a JWT token with a private key? ›

Generate JWT Keys
  1. openssl genrsa -out ./private.key 4096.
  2. ssh-keygen -t rsa -b 4096 -m PEM -f private.key.
  3. openssl rsa -in private.key -pubout -outform PEM -out public.key.
  4. ssh-keygen -f private.key -e -m PKCS8 > public.key.

What type of encryption does JWT use? ›

The issuer generates a hash of the JWT header and payload using SHA256, and encrypts it using the RSA encryption algorithm, and their private key.

Why use JWT instead of token? ›

JWT is suitable for stateless applications, as it allows the application to authenticate users and authorize access to resources without maintaining a session state on the server. OAuth, on the other hand, maintains a session state on the server and uses a unique token to grant access to the user's resources.

When not to use JWT? ›

To reiterate, whatever you do, don't store a JWT in localStorage (or sessionStorage). If any of the third-party scripts you include in your page are compromised, it can access all your users' tokens. To keep them secure, you should always store JWTs inside an HttpOnly cookie.

Is JWT more secure than API key? ›

The credentials can either be a cryptographically secure JSON Web Token (JWT) signed with the client's private key or a secret value generated from your authorization server. A private key JWT is more secure, as you won't risk exposing the secret value that accidentally creates similar access concerns as an API key.

Can a JWT token be hijacked? ›

It is used literally everywhere: from sessions to token-based authentication in OAuth, to custom authentication of all shapes and forms. There is actually a pretty good reason for this wide adoption and that is, for the most part, security and resilience. However, just like any technology, JWT is not immune to hacking.

Do you need a public key for JWT? ›

Every distributed scenario using JWTs should use this signature scheme. For example, in a microservice architecture where JWTs are exchanged, each service should have a public/private key pair.

What is the JWT secret key? ›

Secure: JWTs are digitally signed using either a secret (HMAC) or a public/private key pair (RSA or ECDSA) which safeguards them from being modified by the client or an attacker. Stored only on the client: You generate JWTs on the server and send them to the client. The client then submits the JWT with every request.

How long should a JWT secret key be? ›

The minimum secret length for HMAC: A key of the same size as the hash output (for instance, 256 bits for “HS256”) or larger MUST be used with this algorithm. The minimum key length for RSA: A key of size 2048 bits or larger MUST be used with these algorithms.

Is JWT used for SSO? ›

You can use Single sign-on (SSO) to log into your Freshworks account via JWT. To learn more about SSO, refer to these articles below.

What encoding does JWT use? ›

The format of a JWT token is simple: <base64-encoded header>. <base64-encoded claims>. <signature> . Each section is separated from the others by a period character ( . ).

What protocols use RSA? ›

Many protocols such as Secure Shell (SSH), SSL-TLS, S/MIME, and OpenPGP rely on RSA encryption and secure digital signature functions. The RSA encryption system solves what was once a significant problem in cryptography: how to send a coded message to someone without previously sharing the code with them.

Does HMAC use RSA? ›

The RSA authentication method is almost identical to HMAC. The only difference is that it uses an RSA private key to sign the String-to-Hash and a RSA public key to validate that the signature is valid. RSA keys provide a more secure way of signing your auth headers than using a password.

Top Articles
Turn $10 to $1000: Best Meme Coins with Potential for High Returns Despite Current Market Conditions
ApeCoin Price Prediction: 2024, 2025, 2030
Metallica - Blackened Lyrics Meaning
Monthly Forecast Accuweather
Obor Guide Osrs
Toyota Campers For Sale Craigslist
Boomerang Media Group: Quality Media Solutions
Air Canada bullish about its prospects as recovery gains steam
Prosper TX Visitors Guide - Dallas Fort Worth Guide
Otterbrook Goldens
Google Jobs Denver
Cumberland Maryland Craigslist
The Idol - watch tv show streaming online
Mivf Mdcalc
Visustella Battle Core
Violent Night Showtimes Near Amc Fashion Valley 18
[2024] How to watch Sound of Freedom on Hulu
W303 Tarkov
Oscar Nominated Brings Winning Profile to the Kentucky Turf Cup
George The Animal Steele Gif
Socket Exception Dunkin
Craigslist Motorcycles Orange County Ca
Radio Aleluya Dialogo Pastoral
Munich residents spend the most online for food
Mani Pedi Walk Ins Near Me
Gdlauncher Downloading Game Files Loop
Grandview Outlet Westwood Ky
Faurot Field Virtual Seating Chart
Espn Horse Racing Results
The Ultimate Guide to Extras Casting: Everything You Need to Know - MyCastingFile
Redfin Skagit County
Unable to receive sms verification codes
Rugged Gentleman Barber Shop Martinsburg Wv
Is Light Raid Hard
The Menu Showtimes Near Amc Classic Pekin 14
Baddies Only .Tv
Nail Salon Open On Monday Near Me
EST to IST Converter - Time Zone Tool
Why Holly Gibney Is One of TV's Best Protagonists
Greater Keene Men's Softball
Maxpreps Field Hockey
Craigslist Gigs Wichita Ks
Plead Irksomely Crossword
Paperless Employee/Kiewit Pay Statements
2700 Yen To Usd
Www Usps Com Passport Scheduler
Umiami Sorority Rankings
At Home Hourly Pay
Pulitzer And Tony Winning Play About A Mathematical Genius Crossword
Winta Zesu Net Worth
Vcuapi
Latest Posts
Article information

Author: Eusebia Nader

Last Updated:

Views: 6206

Rating: 5 / 5 (60 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Eusebia Nader

Birthday: 1994-11-11

Address: Apt. 721 977 Ebert Meadows, Jereville, GA 73618-6603

Phone: +2316203969400

Job: International Farming Consultant

Hobby: Reading, Photography, Shooting, Singing, Magic, Kayaking, Mushroom hunting

Introduction: My name is Eusebia Nader, I am a encouraging, brainy, lively, nice, famous, healthy, clever person who loves writing and wants to share my knowledge and understanding with you.