3

Is there a way to convert RSA PEM Public key to XML without using 3rd party library such as BouncyCastle. So far I understood System.Security.Cryptography only recognize xml sring. RSA.FromXmlString(PublicKey)

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArqNpTjJR6+aP7dYNTqIU
OPcpTirmN5JbS+ZL255MByiHWn7AF9DU5Q99TROtGbtqySuyzv3fu28YRRSIwK/J
kMLb50AEe3XvnUoZhN86QLCie3iFIq8kpELmX5v2GxCt15ks+cwGsYGYGGwTZNo2
2Y4W1cRgVBLhhbEbuvybKddi7UsmhJlbvLqinUUGCJFkgCAyIbYYowlUjZhbVjp9
DGiaF7EwpcbcERckYXwnKheejWG0chHL9Nt9YldW33Vjgb6s3A9GNF80XNuqT6GJ
T3h3Ig/aoK/9AIhVvc53atCJEgRnjKgfkYPr3SQoKLH7HDCq2TOwN9N5Mbp0QNvb
kwIDAQAB
-----END PUBLIC KEY-----

thanks in advance

UPDATE

found an answer in here.

stormwild/opensslkey.cs

dins88
  • 165
  • 1
  • 8
  • 2
    If it is a "one time" converting I would use an online service like https://superdry.apphb.com/tools/online-rsa-key-converter to do that. If you like to do it offline (although it's a public key) you can use openssl for this task. If you want to do this programmatically you should kindly edit your question and add a **sample** public key as there are (minimum) 2 different PEM encodings. – Michael Fehr Nov 02 '20 at 15:50
  • @MichaelFehr thanks for the comment. I want to do it in programmatically and updated the question. – dins88 Nov 02 '20 at 16:17
  • 1
    Easy with .NET Core, more difficult with .NET Framework, which is why BouncyCastle is generally used for the latter. The main problem is the key import. A sample, how the import with on-board means is possible, is e.g. the method [`opensslkey.DecodeX509PublicKey`](https://jensign.com/dotnet/opensslkey/opensslkey.cs), which imports a DER encoded key into an `RSACryptoServiceProvider` instance. For the export [`RSA.ToXmlString`](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rsa.toxmlstring?view=netframework-4.8) can be used. – Topaco Nov 02 '20 at 18:36
  • @Topaco thanks for the answer. i just found the opensslkey sourcecode. and plan to used it to since it opensource – dins88 Nov 02 '20 at 18:41
  • @dins88 Huh, Bouncy Castle is meritware, right? You cannot get much more open source than that. However, you can answer your own question instead of editing it. – Maarten Bodewes Nov 02 '20 at 23:07

2 Answers2

5

If you're using .NET Core or .NET 5+, there's a helpful ToXmlString() method on the RSA class.

var privateKey = await File.ReadAllTextAsync("mypemfile.pem");
var rsa = RSA.Create();
rsa.ImportFromPem(privateKey.ToCharArray());
var d = new XmlDocument();
d.LoadXml(rsa.ToXmlString(true));
d.Save("mypemfile.xml");
ScottieMc
  • 656
  • 9
  • 16
  • 1
    Actually you have to use .NET 5+ to have this functionality [as per this answer too](https://stackoverflow.com/a/251757/6357360). – meJustAndrew Feb 07 '22 at 18:27
0

I've used ScottieMc snippet to create a .NET 6.0 Console Application that just do the job:

https://github.com/robyarmenio/PemToXML