private X509Certificate2 EnsurePrivateKey(X509Certificate certificate)
{
if (certificate == null)
{
return null;
}
if (NetEventSource.IsEnabled) NetEventSource.Log.LocatingPrivateKey(certificate, this);
try
{
string certHash = null;
// Protecting from X509Certificate2 derived classes.
X509Certificate2 certEx = MakeEx(certificate);
certHash = certEx.Thumbprint;
if (certEx != null)
{
if (certEx.HasPrivateKey)
{
if (NetEventSource.IsEnabled) NetEventSource.Log.CertIsType2(this);
return certEx;
}
if ((object)certificate != (object)certEx)
{
certEx.Dispose();
}
}
X509Certificate2Collection collectionEx;
// ELSE Try the MY user and machine stores for private key check.
// For server side mode MY machine store takes priority.
X509Store store = CertificateValidationPal.EnsureStoreOpened(_serverMode);
if (store != null)
{
collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false);
if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey)
{
if (NetEventSource.IsEnabled) NetEventSource.Log.FoundCertInStore(_serverMode, this);
return collectionEx[0];
}
}
store = CertificateValidationPal.EnsureStoreOpened(!_serverMode);
if (store != null)
{
collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false);
if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey)
{
if (NetEventSource.IsEnabled) NetEventSource.Log.FoundCertInStore(_serverMode, this);
return collectionEx[0];
}
}
}
catch (CryptographicException)
{
}
if (NetEventSource.IsEnabled) NetEventSource.Log.NotFoundCertInStore(this);
return null;
}