Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#5.0

Extract Keys from Federation Meta Data File (ADFS)

4.00/5 (2 votes)
20 Jun 2014CPOL 14.9K   28  
Quick routine to extract keys from FederationMetaData.xml

Introduction

This is a simple routine to extract the keys from a Federationmetadata.xml file as found on ADFS sites.

Using the Code

To use the code, download the zip file above which contains a simple Visual Studio (2013) project that wraps the below code with a basic file dialog. Nothing special in this code, it simple opens the FederationMetaData.xml file as a string, injects the necessary namespaces to query for the Key Node and then extracts the Base64-encoded key.

That key is loaded into an x509 object in order to write it to disk as a .cer file.

Which allows import into the certificate store on Windows.

It writes out to the same location from which the XML was opened, using a hard-coded name of "ExtractedCertificate" and an iterator number (as usually the keys are included seven times in a Federation Meta data file).

Not more than five minutes' work, but hope it saves someone from scratching their head at how to import the certificate needed to trust a remote ADFS system.

C#
System.IO.StreamReader sr = new
        System.IO.StreamReader(openFileDialog1.FileName);
        XmlDocument document = new XmlDocument();
        document.LoadXml(sr.ReadToEnd());
        XmlNode root = document.DocumentElement;
        XmlNamespaceManager NS = new XmlNamespaceManager(document.NameTable);
        NS.AddNamespace("default", "urn:oasis:names:tc:SAML:2.0:metadata");
        NS.AddNamespace("keys", "http://www.w3.org/2000/09/xmldsig");
        NS.AddNamespace("keys1", "http://www.w3.org/2000/09/xmldsig#");
sr.Close();
         XmlNodeList cert = root.SelectNodes("descendant::keys1:X509Certificate",
         NS); ///KeyDescriptor/KeyInfo/X509Data/X509Certificate
        int i = 1;
        foreach (XmlNode thisNode in cert ){
            string thisText = thisNode.InnerText;
            byte[] keydata = Convert.FromBase64String(thisText);
            var x509c = new X509Certificate2(keydata);
            if(openFileDialog1.CheckPathExists){
                string newCert = System.IO.Path.GetDirectoryName(openFileDialog1.FileName) +
                "\\ExtractedCertificate" + i + ".cer";
                System.IO.File.WriteAllText(newCert, Convert.ToBase64String(x509c.Export(X509ContentType.Cert)));
                i++;
            }
        }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)