private static X509Certificate2 FindCertificate(string certificateSubject)
{
const StoreName StoreName = StoreName.My;
const StoreLocation StoreLocation = StoreLocation.LocalMachine;
var store = new X509Store(StoreName, StoreLocation);
try
{
store.Open(OpenFlags.ReadOnly);
// Find with the FindBySubjectName does fetch all the certs partially matching the subject name.
// Hence, further filter for the certs that match the exact subject name.
List<X509Certificate2> clientCertificates =
store.Certificates.Find(X509FindType.FindBySubjectName, certificateSubject, validOnly: true)
.Cast<X509Certificate2>()
.Where(c => string.Equals(
c.Subject.Split(',').First().Trim(),
string.Concat("CN=", certificateSubject).Trim(),
StringComparison.OrdinalIgnoreCase)).ToList();
if (!clientCertificates.Any())
{
throw new InvalidDataException(
string.Format(CultureInfo.InvariantCulture, "Certificate {0} not found in the store {1}.", certificateSubject, StoreLocation.LocalMachine));
}
X509Certificate2 result = null;
foreach (X509Certificate2 cert in clientCertificates)
{
DateTime now = DateTime.Now;
DateTime effectiveDate = DateTime.Parse(cert.GetEffectiveDateString(), CultureInfo.CurrentCulture);
DateTime expirationDate = DateTime.Parse(cert.GetExpirationDateString(), CultureInfo.CurrentCulture);
if (effectiveDate <= now && expirationDate.Subtract(now) >= TimeSpan.FromDays(1))
{
result = cert;
break;
}
}
return result;
}
finally
{
store.Close();
}
}
我的库中有这段代码,每次创建新请求时,它都会调用此方法。所以基本上每秒的请求数是 1000 次,那么它将被调用 1000 次。当我使用 PerfView 工具时,我注意到这种方法使用了 35% 的 CPU。最大的罪魁祸首是 store.Open 和 store.Certificates.Find 方法。
其他任何人都在他们的代码中发现了类似的问题。此外,如果您可以分享您为解决由此造成的性能影响所做的工作。