2015-07-02 27 views
0

我正在研究一個更大的應用程序,它通過POP3,IMAP或通過從.msg導入文件(從Outlook導出或從Outlook中拖出)。Howto驗證SMIME多部分/簽名應用程序簽名/ x-pkcs7簽名郵件

最近我收到一封附帶「smime.p7m」的電子郵件。 經過進一步的檢查後證明是一個MIME消息

Content-Type:multipart/signed; protocol =「application/x-pkcs7-signature」;

除其他部件使其包含一個部分

內容類型:應用程序/ x-PKCS7簽名; name =「smime.p7s」 Content-Transfer-Encoding:base64 Content-Disposition:attachment; 文件名=「smime.p7s」

我嘗試驗證使用OpenPop爲MIME消息解析器和SignedCms檢查簽名此簽名。我的嘗試是這樣的:

var datapart = OpenPop.MessagePart[...]; 
var part3 = OpenPop.MessagePart[3]; // the signature 

var ci = new ContentInfo(datapart);    
var sCMS = new SignedCms(ci, detached: true); 
sCMS.Decode(part3.Body); 
sCMS.CheckHash(); 

sCMS.CheckSignature(verifySignatureOnly:true); 

但無論怎樣我用datapart我總是

System.Security.Cryptography.CryptographicException 哈希值是不正確的。

如何驗證簽名?

有沒有更好的方法?

+0

我的回答有幫助嗎? – jstedfast

+0

是的,非常感謝。 – DrKoch

回答

1

要做到這一點,最簡單的方法是使用MimeKit(這不僅是開源的,而且還可以免費用於商業用途)。

由於您關心的只是驗證簽名,因此您可以僅使用MimeKit.Cryptography.TemporarySecureMimeContext而不是自行設置(例如README和其他關於如何操作的文檔)。

通常,當接收通過S/MIME簽名的消息,它幾乎總是根級MIME一部分是multipart/signed部分,這使得朝向驗證簽名這個有點更容易(第一步驟是找到multipart/signed部分)。

var signed = message.Body as MultipartSigned; 
if (signed != null) { 
    using (var ctx = new TemporaryMimeContext()) { 
     foreach (var signature in signed.Verify (ctx)) { 
      try { 
       bool valid = signature.Verify(); 

       // If valid is true, then it signifies that the signed 
       // content has not been modified since this particular 
       // signer signed the content. 
       // 
       // However, if it is false, then it indicates that the 
       // signed content has 
       // been modified. 
      } catch (DigitalSignatureVerifyException) { 
       // There was an error verifying the signature. 
      } 
     } 
    } 
} 

您可以在www.mimekit.net/docs找到MimeKit的API文檔。