I am trying to create an X509Certificate2
object in C# from an XML file. The XML file is a SAML
metadata file that we received from a vendor.
I am trying to extract the public key from these XML Elements:
<X509Data>
<X509Certificate>
MIIB7DCCAVmgAwIBAgIQPjHcBTL63bBLuJZ88RcrCjAJBgUrDgMCHQUAMBExDzANBgNVBAMT
BnJvbWVvazAgFw0xMDAzMTUwMjI1MjZaGA8yMTEwMDIxOTAyMjUyNlowETEPMA0GA1UEAxMG
cm9tZW9rMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAu/sBh13A27rR7gJpZsI6zCee
TXNohQWlq2z6Zg8Oxzsy5JoVV
</X509Certificate>
</X509Data>
Is there a way in C# to extract either the .cer file or public key from the XML element?
Randall's answer is correct. But in SAML Token the certificate I believe will always be Base64 encoded. So for posterity, the solution that worked for me was:
var document = new XmlDocument();
document.LoadXml(txtXml.Text);
var certificateStr = document.SelectSingleNode("X509Data/X509Certificate").InnerText;
byte[] data = Convert.FromBase64String(certificateStr);
var x509 = new X509Certificate2(data);
Console.WriteLine("Public Key Format: {0}", x509.PublicKey.EncodedKeyValue.Format(true));
This is a difficult question to answer without knowing how the X509Certificate is encoded, but assuming you have the encoding stuff, you can do something like the following:
var document = new XmlDocument();
document.LoadXml(txtXml.Text);
var cert = document.SelectSingleNode("X509Data/X509Certificate").InnerText;
/*...Decode text in cert here (may need to use Encoding, Base64, UrlEncode, etc) ending with 'data' being a byte array...*/
var x509 = new X509Certificate2(data);
Then you should be able to write the file to disk using standard File I/O logic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With