Thursday, October 29, 2015

IIS private key export as base64 cert.

Problem:

I was trying to export an SSL public/private key from IIS.  This will export only as a pfx.  I needed it as a base64 encoded file.  This often happens with proxy servers which host a front end.  They don't seem to like pfx since they all tend to run Linux.

Solution:

Create a console application and programmatically create the cert file.

  m_X509CertificateThumbprint = Regex.Replace(rawThumbprintString, @"[^\u0000-\u007F]", string.Empty);
            m_X509CertificateThumbprint = rawThumbprintString.Replace("\u200e", string.Empty).Replace("\u200f", string.Empty).Replace(" ", string.Empty);
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);

            //var certificate = store.Certificates.Find(X509FindType.FindByThumbprint,
            //    "‎69c04af8588ec65762de96ddd51d78fa6e47c692", false)[0]; // doesn't matter how you get the cert
            var cert = store.Certificates.Find(X509FindType.FindByThumbprint, m_X509CertificateThumbprint, true);
            if(cert.Count > 0)
            {
                X509Certificate2 full = cert[0];
                Console.WriteLine(full.FriendlyName);
                var exported = full.Export(X509ContentType.Pfx, "1qaz@WSX");
                var base64 = Convert.ToBase64String(exported);
                System.IO.File.WriteAllText(@"C:\viper\aeitt.cer.txt", base64);


            }

            store.Close();

Source:
http://stackoverflow.com/questions/8863785/how-to-get-the-base-64-encoded-value-of-a-certificate-with-private-key
http://stackoverflow.com/questions/11115511/how-to-find-certificate-by-its-thumbprint-in-c-sharp

No comments:

Post a Comment