1 year ago

#317765

test-img

Daniel Botero Correa

Encrypting payload using JWE (Alg: ECDH_ES, Enc: A256GCM) .NET5

Is there a way to encrypt data using Alg: ECDH_ES, Enc: A256GCM in .NET 5 - OS: Linux?

Data to encrypt:

"{\"num\":\"1234567891234567\",\"ram\":\"1223\"}"

What I tried:

I used .NET jose-jwt library to encrypt a payload using Alg: ECDH_ES, Enc: A256GCM and it works pretty good in Windows. The problem is that it doesn't work in Linux because JWT.Encode() expects a CngKey which is only available in Windows platforms. (Check the git issue here with all the code)

string token = Jose.JWT.Encode(json, pubCngKey, JweAlgorithm.ECDH_ES, JweEncryption.A256GCM);

On the other hand, I have come across multiple posts from Scott Brady talking about JWE explaining how to use JWE in .NET Core but I wasn't able to achieve what I needed either.

He has an example of encrypting a JWT Token using System.IdentityModel.Tokens.Jwt but I didn't find a way to use that to achieve encryption using Alg: ECDH_ES, Enc: A256GCM and for any kind of data. In his examples, he is encrypting an Authentication Token and I just want to encrypt a JSON payload like:

"{\"num\":\"1234567891234567\",\"ram\":\"1223\"}"

Even if I wanted to use his method, He achieves encryption with the following code but I haven't been able to load my EC public key as X509Certificate2.

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);

To use Alg: ECDH_ES, Enc: A256GCM with his method I wrote the code below but I couldn't test it because I wasn't able to load my EC public key as X509Certificate2.

EncryptingCredentials = new X509EncryptingCredentials(new X509Certificate2("key_public.cer"), SecurityAlgorithms.EcdsaSha256Signature, SecurityAlgorithms.EcdsaSha256)

When I tried to load my EC public key I get the following exception

Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Cannot find the requested object.

This is my EC Public key generated from a private key with curve prime256v1

-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE6z98vdUZNeuaEXcoxLY9dSylEI7H
Nr+Uj/CYwlbE97l4PB5pZw0R3fKshknUKb2t5I+2v+XD4P9fsqJqBJZhkQ==
-----END PUBLIC KEY-----

c#

encryption

.net-5

jwe

0 Answers

Your Answer

Accepted video resources