DEV Community

Cover image for How to get base64 encoded string of a certificate in C#
Emanuele Bartolesi
Emanuele Bartolesi

Posted on

How to get base64 encoded string of a certificate in C#

In the last few weeks I worked a lot with certificates and authentication with C# and console application.
For a lot of reasons, sometimes, I need a base64 encoded string version of the certificates I have installed locally on my machine.



    public string GetEncodedStringFromCertificate(string certThumbprint, string certPassword)
    {
        var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        store.Open(OpenFlags.ReadOnly);

        var certificate = store.Certificates.Find(X509FindType.FindByThumbprint, certThumbprint, false).First();
        var exp = certificate.Export(X509ContentType.Pfx, certPassword);
        var base64 = Convert.ToBase64String(exp);
        store.Close();

        return base64;
    }


Enter fullscreen mode Exit fullscreen mode

I have created this function above to retrieve a certificate with a Thumbprint and a password.
By the way it's not important the way to retrieve the certificate, but how to export to a base64 encoded string.

In my case I have a lot of Pfx, but you can choose the right certificate type for you.


Thanks for reading this post, I hope you found it interesting!

Feel free to follow me to get notified when new articles are out 🙂

Top comments (1)

Collapse
 
elmalah profile image
Tarek El-Mallah

Thanks, that work for me, I was searching for long time to get base64 from X509 Certificate.