Extract public key from X509 certificate XML file?

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 the provider.

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 a .cer file or public key from an XML element?

+4
source share
2 answers

This is a difficult question to answer, not knowing how the X509Certificate is encoded, but provided that you have the material to encode, 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 can write the file to disk using the standard file I / O logic.

+4
source

Randall's answer is correct. But in SAML Token, a certificate that 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)); 
+6
source

All Articles