Skip to content

Instantly share code, notes, and snippets.

@nanasess
Created August 8, 2017 01:04
Show Gist options
  • Save nanasess/ff8629c476edfddc1b304f9759b9eaa3 to your computer and use it in GitHub Desktop.
Save nanasess/ff8629c476edfddc1b304f9759b9eaa3 to your computer and use it in GitHub Desktop.
RSA public key to JWKs(JSON Web Key Set) for C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
namespace TestCommands
{
class Jwks
{
private const string PUBLIC_KEY = @"-----BEGIN PUBLIC KEY-----
MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQB5uVaCLL+DmPblCSJas1iC
MqY2XI4yZ3w5mj9gcXG9RqjWiZ8hSv+In1pUl4MSVoykd/Sd3khd6kKLt5GI40Ix
rs1f/DZBYdUYgNhc1pJU3AiOFx/xFmVFACwJM+fVkuJ/hXrHDsWK3AQdCcvrIBjs
RstK5ZzJOHW6doMsawle1EGbhxazBglVwE6zgyMAeGehZHzekj9bliEB4Pxn4Eir
VAPN6bbZ0CYygUQiKCV/L6lMR6IMtqG165rj32bOFdm3H8p/XUA5Rzn1HJe6T8JU
gEJRVIMrYegHclOmxS/LhhJZ7uXuDjex6NlciBlbwWXO6RBDyupwYuY7m8DWqML3
AgMBAAE=
-----END PUBLIC KEY-----";
static void Main(string[] args)
{
using (var textReader = new StringReader(PUBLIC_KEY))
{
var pubkeyReader = new PemReader(textReader);
RsaKeyParameters KeyParameters = (RsaKeyParameters)pubkeyReader.ReadObject();
var e = Base64UrlEncoder.Encode(KeyParameters.Exponent.ToByteArrayUnsigned());
var n = Base64UrlEncoder.Encode(KeyParameters.Modulus.ToByteArrayUnsigned());
var dict = new Dictionary<string, string>() {
{"e", e},
{"kty", "RSA"},
{"n", n}
};
var hash = SHA256.Create();
Byte[] hashBytes = hash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(dict)));
JsonWebKey jsonWebKey = new JsonWebKey()
{
Kid = Base64UrlEncoder.Encode(hashBytes),
Kty = "RSA",
E = e,
N = n
};
JsonWebKeySet jsonWebKeySet = new JsonWebKeySet();
jsonWebKeySet.Keys.Add(jsonWebKey);
System.Console.WriteLine(JsonConvert.SerializeObject(jsonWebKeySet));
}
}
}
}
@nanasess
Copy link
Author

nanasess commented Aug 8, 2017

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