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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building a Reddit Scraper in Go: JSON Listings, Pagination, Rate Limits, and Where It Breaks
  • Exploring the DBMS_DEVELOPER Package: JSON Metadata for Oracle Objects
  • When TypeScript Types Meet Untrusted AI: Building Type-Safe LLM Pipelines With Runtime Validation
  • Replacing JSON With Protobuf in Your Microservice Mesh: A Zero-Downtime Migration Blueprint

Trending

  • OpenCode: Setting Up an Open-Source AI Coding Assistant
  • AI Agents and Frontier Models: Insights From The Neuron
  • How to Keep AI Agents From Going Rogue Using Docker Sandbox
  • Why Vulnerability Management Fails Without Reliable Asset Data

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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.

By 
Scott Brady
·
Jan. 28, 19 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
30.7K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Building a Reddit Scraper in Go: JSON Listings, Pagination, Rate Limits, and Where It Breaks
  • Exploring the DBMS_DEVELOPER Package: JSON Metadata for Oracle Objects
  • When TypeScript Types Meet Untrusted AI: Building Type-Safe LLM Pipelines With Runtime Validation
  • Replacing JSON With Protobuf in Your Microservice Mesh: A Zero-Downtime Migration Blueprint

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook