Fetch And Store Public Certificate

I needed to check my signature in the app I was creating, but was wondering where to store the public key.

One of the ideas was to embed it in the binary, but I would like to be able to get the latest one because the update becomes difficult.
So I came up with a way to store it in the X509Store.

The implementation is as follows.

using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;

namespace ConsoleApp3
    class Program
        static void Main(string[] args)
            var cert = new Program().GetPublicCertAsync("blog.iwate.me").Result;
            var rsa = cert.GetRSAPublicKey();
        public async Task<X509Certificate2> GetPublicCertAsync(string domain)
            var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);


            var collection = store.Certificates.Find(X509FindType.FindBySubjectName, domain, true);

            if (collection.Count > 0)
                return collection[0];

            X509Certificate2 certificate = null;
            await new HttpClient(new HttpClientHandler
                UseDefaultCredentials = true,
                ServerCertificateCustomValidationCallback = (sender, cert, chain, error) =>
                    if (error != SslPolicyErrors.None || !cert.Verify())
                        return false;

                    certificate = cert;
                    return true;
            }).SendAsync(new HttpRequestMessage(HttpMethod.Head, $"https://{domain}/"));

            return certificate;

You'll only receive email when they publish something new.

More from iwate
All posts