使用Java Mail验证带有Outlook 2013签名的电子邮件

时间:2016-01-11 08:48:37

标签: java outlook javamail digital-signature x509certificate

我发送带有签名的电子邮件到我的收件箱。然后我使用Java Mail接收邮件并验证签名。但总是会出现错误消息“消息摘要属性值与计算值不匹配”。

org.bouncycastle.cms.CMSSignerDigestMismatchException: message-digest attribute value does not match calculated value
at org.bouncycastle.cms.SignerInformation.doVerify(SignerInformation.java:517)
at org.bouncycastle.cms.SignerInformation.verify(SignerInformation.java:601)

我使用maven

    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.5</version>
    </dependency>
    <!-- Bouncy Castle Provider -->
    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-jdk15on</artifactId>
        <version>1.54</version>
    </dependency>
    <!-- BC Mail -->
    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcmail-jdk15on</artifactId>
        <version>1.54</version>
    </dependency>

这条线我有一个例外:

 verify = signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificate));

以下是我的代码:

    public static void receiveSignedMail(Message msg) throws MessagingException {
    try {
        SMIMESigned signed = new SMIMESigned((MimeMultipart) msg.getContent());
        if (isValid(signed)) {
            System.out.println("verification succeeded");
        } else {
            System.out.println("verification failed");
        }
        signed = new SMIMESigned((MimeMultipart) msg.getContent());
         MimeBodyPart content = signed.getContent();
         System.out.println("Content: " + content.getContent());
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}

public static boolean isValid(CMSSignedData signedData) {
    try {
        SignerInformationStore signers = signedData.getSignerInfos();
        Iterator<SignerInformation> it = signers.getSigners().iterator();
        boolean verify = false;
        while (it.hasNext()) {
            SignerInformation signer = it.next();
            org.bouncycastle.util.Store store = (org.bouncycastle.util.Store) signedData.getCertificates();
            Collection certCollection = ((org.bouncycastle.util.Store) store).getMatches(signer.getSID());
            Iterator certIt = certCollection.iterator();
            X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
            X509Certificate certificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
            verify = signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificate));
        }
        return verify;
    } catch (Exception e) {
        e.printStackTrace(System.out);
        return false;
    }
}

public static Folder getFolder(String folderName) {
    try {
        String host = "your mail server";
        boolean auth = true;
        /* You must use SSL for incoming mail, SSL ports are 993 for IMAP and 995 for POP3 */
        /* To support SSL, using protocl 'pop3s' or 'imaps' */
        String port = "993";
        String receivingProtocol = "imaps";
        String username = "your email address";
        String password = "your email password";

        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", auth);
        props.put("mail.store.protocol", receivingProtocol);
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore(receivingProtocol);
        store.connect(host, username, password);
        Folder folder = store.getFolder(folderName);
        folder.open(Folder.READ_WRITE);
        return folder;
    } catch (Exception e) {
        e.printStackTrace(System.out);
        return null;
    }
}

运行它的主要方法

public static void main(String args[]) {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    try {
        String inbox = "Your Inbox";
        Folder folder = getFolder(inbox);
        SearchTerm st = new OrTerm(new FromStringTerm("search condition"), new SubjectTerm("search condition"));
        Message[] messages = folder.search(st);
        int mailCounts = messages.length;
        System.out.println("Found: " + mailCounts + " mails matched with the condition.");

        if (messages.length == 0) {
            System.out.println("No Message!");
        }
        for (int i = 0; i < messages.length; i++) {
            System.out.println("the " + (i + 1) + " mail" + "------------------------------------------------");
            MimeMessage mail = (MimeMessage) messages[i];
            String out_from = ((InternetAddress) messages[i].getFrom()[0]).getAddress();
            System.out.println("From:" + out_from);
            System.out.println("Subject:" + messages[i].getSubject());
            System.out.println("Type: " + mail.getContentType());
            if (mail.isMimeType("multipart/signed")) {
                System.out.println("a signed mail");
                receiveSignedMail(mail);
            }
        }
        folder.close(true);
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}

1 个答案:

答案 0 :(得分:0)

我与所有其他电子邮件客户端(Thunderbird,Outlook等)都存在相同的问题,但是我能够解决它。我认为此问题是由 javax.mail 库中的错误引起的。

我正在使用以下Maven依赖项:

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

<dependency>
     <groupId>org.bouncycastle</groupId>
     <artifactId>bcprov-jdk15on</artifactId>
     <version>1.62</version>
</dependency>

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcmail-jdk15on</artifactId>
    <version>1.62</version>
</dependency>

解决方案:

通过IMAP从电子邮件服务器轮询电子邮件时,您会以 Message 对象数组的形式接收它们:

Message[] messages = pollFolder.getMessages();

现在,您将遍历此数组并分别处理每条消息。这意味着,您正在直接使用 Message 对象。

但是,如果您想通过Bouncy Castle验证邮件的签名,则需要使用 MimeMessage 对象(请参见Bouncy Castle的official example代码;代码行93)

要将消息转换为 MimeMessage ,通常需要通过以下方式投射对象:

MimeMessage mimeMsg = (MimeMessage) message;

但是由于某些原因,此操作无法正常工作,因此稍后在通过Bouncy Castle验证电子邮件签名时遇到以下异常:org.bouncycastle.cms.CMSSignerDigestMismatchException: message-digest attribute value does not match calculated value

作为解决方法,我要做的是在 MimeMessage 构造函数的作用下复制已投射的 MimeMessage 对象! !

所以这为我解决了这个问题

MimeMessage mimeMsg = new MimeMessage((MimeMessage) message);

这是完整的工作代码

Message message = // get Message from folder...
MimeMessage mimeMsg = new MimeMessage((MimeMessage) message);
boolean emailSignatureValid = verifySignature(mimeMsg);

 // code from Bouncy Castle
 public boolean verifySignature(MimeMessage signedMimeMessage) {
    try {
        if (signedMimeMessage.isMimeType("multipart/signed")) {
            SMIMESignedParser s = new SMIMESignedParser(new JcaDigestCalculatorProviderBuilder().build(), (MimeMultipart) signedMimeMessage.getContent());
            return verify(s);
        } else if (signedMimeMessage.isMimeType("application/pkcs7-mime")) {
            SMIMESignedParser s = new SMIMESignedParser(new JcaDigestCalculatorProviderBuilder().build(), signedMimeMessage);
            return verify(s);
        } else {
            throw new IllegalArgumentException("This mimeMessage is not signed: " + EmailPrinter.printMessage(signedMimeMessage));
        }
    } catch (Exception e) {
        log.error("Could not verify signature of mimeMessage", e);
        return false;
    }
}

 // code from Bouncy Castle
 private static boolean verify(SMIMESignedParser s) throws Exception {

    Store certs = s.getCertificates();
    SignerInformationStore signers = s.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certs.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();
        X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate((X509CertificateHolder) certIt.next());
        try {
            return signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert));
        } catch (Exception e) {
            log.error("Error occured during verification",e);
        }
    }

    return false;
}

我知道这是一个怪异的解决方法,但这是解决问题的唯一方法。我希望您也觉得它有用。

欢呼!

BEEveloper