我使用下面的代码在asp.net Web服务中使用数字证书签名消息。 签名工作正常,期望signedMessage.ComputeSignature行需要30到40秒,因为这是我面临超时异常。当我在Windows窗体应用程序下运行时,相同的代码产生的结果只有几分之一秒。任何线索或帮助。
public static string Encrypt(string fullMessage, string certificateName, bool deAttch)
{
X509Certificate2 signer = GetCertificate(certificateName);
byte[] contentBytes = Encoding.ASCII.GetBytes(fullMessage);
Oid contentOid = new Oid("1.2.840.113549.1.7.1", "PKCS 7 Data");
SignedCms signedMessage = new SignedCms(new ContentInfo(contentOid, contentBytes), deAttch);
signedMessage.ComputeSignature(new CmsSigner(signer));
byte[] signedBytes = signedMessage.Encode();
return Convert.ToBase64String(signedBytes).Trim();
}
答案 0 :(得分:3)
我不确定这是否应该是一个答案(我不知道它会产生什么影响,但我会发现)。只是设置一个属性
cert.IncludeOption = X509IncludeOption.EndCertOnly;
的
CmsSigner cert = new CmsSigner(signer);
之前我使用构造函数创建对象并直接传递给方法。现在它工作正常,而不是花费那么多时间。
public static string Encrypt(string fullMessage, string certificateName, bool deAttch)
{
X509Certificate2 signer = GetCertificate(certificateName);
byte[] contentBytes = Encoding.ASCII.GetBytes(fullMessage);
Oid contentOid = new Oid("1.2.840.113549.1.7.1", "PKCS 7 Data");
SignedCms signedMessage = new SignedCms(new ContentInfo(contentOid, contentBytes), deAttch);
CmsSigner cert = new CmsSigner(signer);
cert.IncludeOption = X509IncludeOption.EndCertOnly;
signedMessage.ComputeSignature(cert);
byte[] signedBytes = signedMessage.Encode();
return Convert.ToBase64String(signedBytes).Trim();
}
private static X509Certificate2 GetCertificate(string certificateName)
{
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
X509Certificate2 certificate = store.Certificates.Cast<X509Certificate2>().Where(cert => cert.Subject.IndexOf(certificateName) >= 0).FirstOrDefault();
if (certificate == null)
throw new Exception("Certificate " + certificateName + " not found.");
return certificate;
}