DEV Community

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

Posted on

3

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 πŸ™‚

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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.

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay