C#使用SignedCms验证数字签名

时间:2011-09-28 06:43:29

标签: c# digital-signature x509certificate pkcs#7

我收到CryptographicException“哈希值不正确。”我试过verifyCms.CheckSignature(true); (同样的错误) 我试图在ContentInfo中添加整个邮件(发件人,主题,正文,HTML部分...)(同样的错误)

 public static bool Verify(byte[] signature, X509Certificate2 certificate)
{
       X509Certificate2 cert=new X509Certificate2(@"D:\Work\Digital Signature\smime.p7s");
   certificate = cert;

    if(signature == null)
        throw new ArgumentNullException("signature");
    if(certificate == null)
        throw new ArgumentNullException("certificate");

    //the text from the body of the mail    
    string text = "FINAL TEST SIGNED";
    //hash the text 
     // Methode 3 for Hashing
            System.Security.Cryptography.SHA1 hash3 = System.Security.Cryptography.SHA1.Create();
            System.Text.UnicodeEncoding encoder = new System.Text.UnicodeEncoding();
            byte[] combined = encoder.GetBytes(text);
            byte[] hash3byte = hash3.ComputeHash(combined);

    //Adding the text from the email, to a contentInfo 
      ContentInfo content = new ContentInfo(hash3byte);

    // decode the signature
    SignedCms verifyCms = new SignedCms(content,true);
    verifyCms.Decode(signature);

    // verify it
    try
    {
        verifyCms.CheckSignature(new X509Certificate2Collection(certificate), false);
        return true;
    }
    catch(CryptographicException)
    {
        return false;
    }
} 

问题出在哪里?

1 个答案:

答案 0 :(得分:0)

你可以看到我的帖子 How to Use RSAEncryption to create PKCS7/CMS with SHA1 digest?

只需将Oid'SHA1'更改为您需要的算法。