JSON Web Encryption (JWE) in .NET Core

C#

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 a simple, secure structure in which 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.

Skip to code.

.NET Core

JWE Format

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

eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGVuYyNyc2Etb2FlcCIsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJraWQiOiI2QjdBQ0M1MjAzMDVCRkRCNEY3MjUyREFFQjIxNzdDQzA5MUZBQUUxIiwidHlwIjoiSldUIn0.DaE3c9YeJck4ZMEVk29Wy0JvQ7XJmoNpFahZHQ1ksPiMrflugbozxyuzSRNWFCUIrDu2r3_5X_F8WxdC-qXN9xZAgD35aWGuQ6lM1JrGGXrSQyXNrsIn2P7Abmqwlifq3PaQmsYbuiVOYSiYQ5q-jxxR49j-y6IckBt8FlF5S2EitKHE-3p6Z6QG01vuvcaEub9iK4bgmwyr7TCmrCMN-7bKbp9l5Mtx2ejoWfPnCbZUm6EepN7fomKLaYHaAFun33IVULa9kJuo0Ah_qb9UD0lc0aVkkcStOxzMWaA8TDq4pQwe78luN8HRvrxcqqifwQB6rmKuX_kXiGLzt2DeEw.oCGmp9GyWwUYDKa3DqWpFA.224dBcDP-bcGua7_oTqujA3d4S-0eiuPc_z-qLNImu484GgUYE-cq9Y19OtF0LfpCegYMI0fq6z7yDd35vPaH5OrPnrQC4MYRLHqQEFOYj85BgKSOgN_GC5vcO9VPocgolbh4tsPWZO4J6fZAuEM5druvC_mGHa8pQx_xeLplLw.DNKMZutgAmwBlHvDe2t06g

Encrypted JWTs comprise of 5 sections:

JWE Protected Header

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

eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGVuYyNyc2Etb2FlcCIsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJraWQiOiI2QjdBQ0M1MjAzMDVCRkRCNEY3MjUyREFFQjIxNzdDQzA5MUZBQUUxIiwidHlwIjoiSldUIn0

Which, when 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 itself 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

The initialization vector used when encrypting the plaintext:

oCGmp9GyWwUYDKa3DqWpFA

JWE Ciphertext

The plain text, protected using authenticated encryption using 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!