Skip to content

Instantly share code, notes, and snippets.

@zerda
Created July 30, 2019 16:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerda/5f3b30bd576835c8a8a9ebf659c50979 to your computer and use it in GitHub Desktop.
Save zerda/5f3b30bd576835c8a8a9ebf659c50979 to your computer and use it in GitHub Desktop.
Convert an RSA to JsonWebKey format
// nuget package reference with:
// - System.IdentityModel.Tokens.Jwt
using System;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Microsoft.IdentityModel.Tokens;
static void Main(string[] args) {
var provider = new RSACryptoServiceProvider(2048);
var key = new RsaSecurityKey(provider.ExportParameters(true));
var jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(key);
jwk.KeyId = "authentication";
jwk.Use = "sig";
jwk.Alg = "RS256";
var json = JsonConvert.SerializeObject(jwk);
Console.WriteLine(json);
}
@afarber
Copy link

afarber commented Nov 26, 2022

using Microsoft.IdentityModel.Tokens;
using System.Security.Cryptography;
using static System.IdentityModel.Tokens.Jwt.JsonExtensions;

RSA rsa = RSA.Create(2048);
RSAParameters parameters = rsa.ExportParameters(false); // do not export private key
RsaSecurityKey rsaSecurityKey = new(parameters);
JsonWebKey jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(rsaSecurityKey);

// JsonExtensions.SerializeToJson produces better output than Newtonsoft - because the former can be converted back to JWK:
Console.WriteLine(SerializeToJson(jwk));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment