私は、次のことを行うことでこの問題を解決できました。これが役立ちます。
public static System.Security.Cryptography.X509Certificates.StoreName StoreName
{
get
{
StoreName storeName = StoreName.My;
if (WebConfigurationManager.AppSettings[SigningStoreName] != null)
storeName = (StoreName)Enum.Parse(typeof(StoreName), WebConfigurationManager.AppSettings[SigningStoreName]);
return storeName;
}
}
public static System.Security.Cryptography.X509Certificates.StoreLocation StoreLocation
{
get
{
StoreLocation storeLocation = StoreLocation.CurrentUser;
if (WebConfigurationManager.AppSettings[SigningStoreLocation] != null)
storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), WebConfigurationManager.AppSettings[SigningStoreLocation]);
return storeLocation;
}
}
public static SigningCredentials GetSigningCredentials()
{
X509Certificate2 cert = CertificateUtil.GetCertificate(StoreName, StoreLocation, WebConfigurationManager.AppSettings[Common.SigningSubjectNameOrThumbprint]);
string signatureAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"
, digestAlgorithm = "http://www.w3.org/2000/09/xmldsig#sha1";
RSACryptoServiceProvider rsa = cert.PrivateKey as RSACryptoServiceProvider;
if (rsa == null) rsa = RSA.Create() as RSACryptoServiceProvider;
RsaSecurityKey rsaKey = new RsaSecurityKey(rsa);
RsaKeyIdentifierClause rsaClause = new RsaKeyIdentifierClause(rsa);
SecurityKeyIdentifier signingSki = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { rsaClause });
SigningCredentials signingCredentials = new SigningCredentials(rsaKey, signatureAlgorithm, digestAlgorithm, signingSki);
return signingCredentials;
}
public static X509Certificate2 GetCertificate(StoreName name, StoreLocation location, string subjectNameOrThumbprint)
{
X509Store store = new X509Store(name, location);
X509Certificate2Collection certificates = null;
store.Open(OpenFlags.ReadOnly);
try
{
X509Certificate2 result = null;
certificates = store.Certificates;
if (certificates != null && certificates.Count > 0)
{
result = (from X509Certificate2 cert in certificates
where !string.IsNullOrWhiteSpace(cert.Thumbprint)
&& cert.Thumbprint.ToLower().Replace(" ", "") == subjectNameOrThumbprint.ToLower().Replace(" ", "")
select cert
).FirstOrDefault();
if (result == null)
result = (from X509Certificate2 cert in certificates
where cert.SubjectName != null
&& cert.SubjectName.Name.ToLower().Replace(" ", "") == subjectNameOrThumbprint.ToLower().Replace(" ", "")
select cert
).FirstOrDefault();
}
string errMsg = string.Format("{0} - {1} in {2}", name.ToString(), subjectNameOrThumbprint, location.ToString());
if (result == null)
throw new ApplicationException(string.Format("No certificate was found for {0} ", errMsg));
else if (result.Verify() == false)
throw new ApplicationException(string.Format("Unable to verify certificate for {0}", errMsg));
return result;
}
finally
{
store.Close();
}
}