using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
public static void Main()
var serializedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw8aoKG/l1bmCJehOhgmz1KVF27NRUwy8uc5l7/nOqLsoWjyprZCb0MlOA2VBH0okvIamXu8xXkup7tvBRUXUEKQBRrVR2shzwl2NAgdNkgNU50Olm1ruYiHu58ruwZdRnWvckXW5vJlCjeg/X/XJ0R8VtP91r2xli0tn4W/l5l4CNR7e6QbizoKb+/OwpHmL4uIQzlvKy7Yurjk5f8qTSarMns5Yb/HSiZl2JJgu6eWwqSt/ErxqwCknzHYFw91eCRoHmQnAXYS8nMuypLM74mOZJUGdByYOR5f3fTve8UrxuteoVGHdZwEbE+hhx+THFMv68Yy6B5niGQ8i1rBBCwIDAQAB";
var publicKey = (Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)Org.BouncyCastle.Security.PublicKeyFactory.CreateKey(Convert.FromBase64String(serializedPublicKey));
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
Console.WriteLine(FormatPem(Convert.ToBase64String(publicKeyInfo.GetEncoded()), "PUBLIC KEY"));
public static byte[] Decode(string arg)
case 2: s += "=="; break;
default: throw new Exception("Illegal base64url string!");
return Convert.FromBase64String(s);
private static string FormatPem(string pem, string keyType)
var sb = new StringBuilder();
sb.AppendFormat("-----BEGIN {0}-----\n", keyType);
int line = 1, width = 64;
while ((line - 1) * width < pem.Length)
int startIndex = (line - 1) * width;
int len = line * width > pem.Length
? pem.Length - startIndex
sb.AppendFormat("{0}\n", pem.Substring(startIndex, len));
sb.AppendFormat("-----END {0}-----\n", keyType);