public void LoadCertificate(HardwareCertificateUnlocker unlocker) { Certificate?.Dispose(); using (var store = new X509Store(StoreName, StoreLocation)) { store.Open(OpenFlags.ReadOnly); var certificates = store.Certificates.OfType <X509Certificate2>() .Where(c => Thumbprint.Equals(c.Thumbprint, StringComparison.InvariantCultureIgnoreCase)).ToArray(); if (certificates.Length == 0) { throw new CertificateNotFoundException($"No certificate with the thumbprint '{Thumbprint}' found"); } Certificate = certificates.FirstOrDefault(c => c.HasPrivateKey); if (Certificate == null) { throw new CertificateNotFoundException($"Certificate with thumbprint '{Thumbprint}' has no private key"); } // For SmartCards/Hardware dongles we create a new RSACryptoServiceProvider with the corresponding pin var rsa = (RSACryptoServiceProvider)Certificate.PrivateKey; if (rsa.CspKeyContainerInfo.HardwareDevice) { var keyPassword = new SecureString(); var decrypted = DataProtector.UnprotectData(TokenPin); foreach (var c in decrypted) { keyPassword.AppendChar(c); } var csp = new CspParameters(1 /*RSA*/, rsa.CspKeyContainerInfo.ProviderName, rsa.CspKeyContainerInfo.KeyContainerName, new System.Security.AccessControl.CryptoKeySecurity(), keyPassword); var oldCert = Certificate; Certificate = new X509Certificate2(oldCert.RawData) { PrivateKey = new RSACryptoServiceProvider(csp) }; oldCert.Dispose(); unlocker?.RegisterForUpdate(this); } } }