DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Low-Code Development: Learn the concepts of low code, features + use cases for professional devs, and the low-code implementation process.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

Getting Started With Jenkins: Learn fundamentals that underpin CI/CD, how to create a pipeline, and when and where to use Jenkins.

Related

  • Under the Hood of .NET-Based Lambda Function Parameters
  • Unlocking the Power of Postgres Listen/Notify: Building Scalable Solution With Spring Boot Integration
  • Accelerating Insights With Couchbase Columnar
  • Exploring ML.NET Catalogs and Use Cases

Trending

  • Node.js Unveiled: Why You Should Use It for Enterprise Apps
  • What’s New Between Java 17 and Java 21?
  • New LAMP Stack: Illuminating Innovation in Generative AI Development
  • Challenges of Legacy System Integration: An In-Depth Analysis
  1. DZone
  2. Coding
  3. Languages
  4. JSON Web Encryption (JWE) in .NET Core

JSON Web Encryption (JWE) in .NET Core

Learn how you can send sensitive data in JWT.

Scott Brady user avatar by
Scott Brady
·
Jan. 28, 19 · Tutorial
Like (4)
Save
Tweet
Share
24.0K Views

Join the DZone community and get the full member experience.

Join For Free

A signed JSON Web Token (JWT) is one of the most useful and common constructs you’ll see floating around modern security systems. These tokens give us simple, secure structures that we can use to transfer data and verify that it has not been tampered with. However, what about when we need to send sensitive data within a JWT?

To solve this issue, we have JSON Web Encryption (JWE), enabling us to encrypt a token so that only the intended recipient can read it.

In this article, we’re going to look at how we can protect sensitive data within our JWTs in .NET Core, using JWEs and the various token libraries available to us.

JWE Format

We’re going to use JWE Compact Serialization (as opposed to JWE JSON Serialization), which looks something like the following:

Encrypted JWTs comprise of five sections:

JWE Protected Header

This is the header of the JWE itself, describing the wrapped token:

eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGVuYyNyc2Etb2FlcCIsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJraWQiOiI2QjdBQ0M1MjAzMDVCRkRCNEY3MjUyREFFQjIxNzdDQzA5MUZBQUUxIiwidHlwIjoiSldUIn0


In this case, base64 decoded has the value of:

{
  "alg": "http://www.w3.org/2001/04/xmlenc#rsa-oaep",
  "enc": "A128CBC-HS256",
  "kid": "6B7ACC520305BFDB4F7252DAEB2177CC091FAAE1",
  "typ": "JWT"
}


Here, our algorithm (alg) value is http://www.w3.org/2001/04/xmlenc#rsa-oaep, which describes how the Content Encryption Key (CEK) was encrypted. The encryption algorithm (enc) value is A128CBC-HS256, which is how the plaintext was encrypted using the CEK. This encryption algorithm must allow for authentication encryption.

In this instance, the Key ID (kid) value references the public key that was used to encrypt the data.

Check out the JWE specification for further header parameters.

JWE Encrypted Key

This is the Content Encryption Key (CEK), a symmetric key that was generated to encrypt the PlainText and then encrypted using the recipients public key (using the algorithm in the header (http://www.w3.org/2001/04/xmlenc#rsa-oaep)). This is known as key wrapping.

DaE3c9YeJck4ZMEVk29Wy0JvQ7XJmoNpFahZHQ1ksPiMrflugbozxyuzSRNWFCUIrDu2r3_5X_F8WxdC-qXN9xZAgD35aWGuQ6lM1JrGGXrSQyXNrsIn2P7Abmqwlifq3PaQmsYbuiVOYSiYQ5q-jxxR49j-y6IckBt8FlF5S2EitKHE-3p6Z6QG01vuvcaEub9iK4bgmwyr7TCmrCMN-7bKbp9l5Mtx2ejoWfPnCbZUm6EepN7fomKLaYHaAFun33IVULa9kJuo0Ah_qb9UD0lc0aVkkcStOxzMWaA8TDq4pQwe78luN8HRvrxcqqifwQB6rmKuX_kXiGLzt2DeEw


JWE Initialization Vector

This is the initialization vector used when encrypting the plaintext:

oCGmp9GyWwUYDKa3DqWpFA


JWE Ciphertext

The plain text is protected using authenticated encryption from our encryption algorithm (A128CBC-HS256), with the CEK as the encryption key, the JWE initialization vector, and the “Additional Authenticated Data,” which, when using compact serialization, is the encoded JWE-protected header:

224dBcDP-bcGua7_oTqujA3d4S-0eiuPc_z-qLNImu484GgUYE-cq9Y19OtF0LfpCegYMI0fq6z7yDd35vPaH5OrPnrQC4MYRLHqQEFOYj85BgKSOgN_GC5vcO9VPocgolbh4tsPWZO4J6fZAuEM5druvC_mGHa8pQx_xeLplLw


Which, when decrypted, looks like:

{{}.{"sub":"123","nbf":1547370520,"exp":1547374120,"iat":1547370520,"iss":"me","aud":"me"}}


JWE Authentication Tag

As a result of performing authenticated encryption, we also receive an authentication tag:

DNKMZutgAmwBlHvDe2t06g


This value is then used during decryption to ensure integrity (the same value is outputted as a result of decryption).

To find out more about JWEs, check out RFC7516.

JWE Tokens in .NET Core

The first thing we’ll need is the latest version of `System.IdentityModel.Tokens.Jwt:'

install-package System.IdentityModel.Tokens.Jwt


Creating a JWE Token

We can now use JwtSecurityTokenHandler just like we normally would, but this time supplying some EncryptingCredentials. This is the public key of the recipient (whoever needs to read the token).

var handler = new JwtSecurityTokenHandler();

var tokenDescriptor = new SecurityTokenDescriptor
{
    Audience = "you",
    Issuer = "me",
    Subject = new ClaimsIdentity(new List<Claim> {new Claim("sub", "scott")}),
    EncryptingCredentials = new X509EncryptingCredentials(new X509Certificate2("key_public.cer"))
};

string token = handler.CreateEncodedJwt(tokenDescriptor);


By default, X509EncryptingCredentials will use a key wrapping algorithm of http://www.w3.org/2001/04/xmlenc#rsa-oaep and an encryption algorithm of A128CBC-HS256 (AES-128-CBC with HMAC-SHA256 for authentication). The JWE specification typically uses AES-256-GCM, but GCM support in .NET is a bit patchy. GCM support should be with us in .NET Core 3.0. If you want to override these defaults, there’s overrides on the X509EncryptingCredentials.

Reading a JWE Token

To read the encrypted JWT, we need to have the corresponding private key to the public key that was used to encrypt it:

var handler = new JwtSecurityTokenHandler();
var claimsPrincipal = handler.ValidateToken(
    token,
    new TokenValidationParameters
    {
        ValidAudience = "you",
        ValidIssuer = "me",
        RequireSignedTokens = false,
    TokenDecryptionKey = new X509SecurityKey(new X509Certificate2("key_private.pfx", "idsrv3test"))
    },
    out SecurityToken securityToken);


Here, we get access to both the parsed security token and a claims principal that represents the token’s payload.

That’s all there is to it!

JSON .NET

Published at DZone with permission of Scott Brady. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Under the Hood of .NET-Based Lambda Function Parameters
  • Unlocking the Power of Postgres Listen/Notify: Building Scalable Solution With Spring Boot Integration
  • Accelerating Insights With Couchbase Columnar
  • Exploring ML.NET Catalogs and Use Cases

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: