LoginSignup
0
3

More than 5 years have passed since last update.

RSA 公開鍵を C# で JWKs(JSON Web Key Set) に出力する

Posted at

jose-jwt など 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));
            }
        }
    }
}

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3