Pergunta

I am signing message using digital certificate in a asp.net web service using below code. Signing is working fine expect signedMessage.ComputeSignature line is taking up to 30 to 40 seconds because of this i am face timeout exception. The same code when i am running under windows forms application is producing result in fraction of second. Any clue or help.

   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();
        }
Foi útil?

Solução

I am not sure whether this should be a answer (I don't know what impact it cause, but i will find out). Just setting a property

cert.IncludeOption = X509IncludeOption.EndCertOnly;    

of

CmsSigner cert = new CmsSigner(signer);

where previously i was creating object using constructor and passing directly to method. Now it is working fine and not taking that much time.

   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;
    }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top