using System.Security.Cryptography;
public static void Main()
bool useRandomKey = true;
using (var rsa = createRSA(useRandomKey))
acctNbr = "4097581122063621"
string jsonPayload = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
string jwe = Jose.JWT.Encode(jsonPayload, rsa, JweAlgorithm.RSA1_5, JweEncryption.A128CBC_HS256);
Console.WriteLine("Generated JWE:");
string decryptedPayload = Jose.JWT.Decode(jwe, rsa);
Console.WriteLine("Decrypted Payload:");
Console.WriteLine(decryptedPayload);
Console.WriteLine("Public Key: ");
Console.Write(ExportPublicKeyToPem(rsa));
Console.WriteLine("Private Key: ");
Console.Write(ExportPrivateKeyToPem(rsa));
private static RSA createRSA(bool random)
rsa = new RSACryptoServiceProvider(2048);
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA/CJWWuvBi66UjwGYVkub
8LehtdULhDT9wsC8DpPPvJvTes4S45zvJT8GAm5nS0goYkW8UUMIRC+g47NY40a9
/bbtBLa9JhYkLyX/zEPvc/Z5u7Nmgup4LLA/0tV2CU50HHP4TBlUDOoQ/eU8XxfW
cKzAsVH62e/rIuSCCCW5CP3Fx7nek+rhasKPTLPAXG46uNei85lM38RLp8v0q9BU
jowfSfVQ5Ge+4d0unekMipLqz0j3c6faPbR2xmnBXmW8ET0CPQl+V4RZ/xNMZBFK
ymcTySeYG5YrDhr6T3FaFpWTNZldxsVNyw5oDyYnH5jtmcdzuDeZUq5HzZo9VSXb
-----END PUBLIC KEY-----";
rsa = PemReader.ImportPublicKey(publicKeyPem);
private static string ExportPublicKeyToPem(RSA rsa)
var sb = new StringBuilder();
sb.AppendLine("-----BEGIN PUBLIC KEY-----");
sb.AppendLine(Convert.ToBase64String(rsa.ExportSubjectPublicKeyInfo(), Base64FormattingOptions.InsertLineBreaks));
sb.AppendLine("-----END PUBLIC KEY-----");
private static string ExportPrivateKeyToPem(RSA rsa)
var sb = new StringBuilder();
sb.AppendLine("-----BEGIN PRIVATE KEY-----");
sb.AppendLine(Convert.ToBase64String(rsa.ExportPkcs8PrivateKey(), Base64FormattingOptions.InsertLineBreaks));
sb.AppendLine("-----END PRIVATE KEY-----");
public static RSA ImportPublicKey(string pem)
var keyData = ReadPem(pem, "PUBLIC KEY");
rsa.ImportSubjectPublicKeyInfo(keyData, out _);
private static byte[] ReadPem(string pem, string section)
var header = $"-----BEGIN {section}-----";
var footer = $"-----END {section}-----";
var start = pem.IndexOf(header, StringComparison.Ordinal);
var end = pem.IndexOf(footer, start, StringComparison.Ordinal);
if (start < 0 || end < 0)
throw new ArgumentException("PEM format is incorrect");
var base64 = pem[start..end].Replace("\r", "").Replace("\n", "").Replace(" ", "").Replace("\t", "");
return Convert.FromBase64String(base64);