Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract public key from an XML file with X509certificate?

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?

like image 773
Yousuf Avatar asked Nov 30 '12 06:11

Yousuf


2 Answers

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));
like image 53
Sebastian K Avatar answered Oct 19 '22 10:10

Sebastian K


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.

like image 32
Randall Borck Avatar answered Oct 19 '22 10:10

Randall Borck