Using Java 7 to Verify OpenSSL Generated S/MIME Digital Signature Files

后端 未结 1 858
孤城傲影
孤城傲影 2021-01-19 06:50

We have a process that uses OpenSSL to generate S/MIME digital signatures which need to be verified later using Java 7. On one side we use OpenSSL to read in text files and

相关标签:
1条回答
  • 2021-01-19 07:24

    This can be done using the Bouncy Castle Crypto APIs where you can use the following official example as reference, https://github.com/bcgit/bc-java/blob/master/mail/src/main/java/org/bouncycastle/mail/smime/examples/ValidateSignedMail.java.

    For a simpler example to perform a full validation of a signed email including the certification chain you would do something like this with org.bouncycastle:bcmail-jdk15on:1.52:

    import org.bouncycastle.cms.SignerInformation;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    import org.bouncycastle.mail.smime.validator.SignedMailValidator;
    
    import javax.mail.internet.MimeMessage;
    import java.io.FileInputStream;
    import java.security.KeyStore;
    import java.security.Security;
    import java.security.cert.PKIXParameters;
    
    public class SignedMailValidatorExample {
        public static void main(String[] args) throws Exception {
            Security.addProvider(new BouncyCastleProvider());
            FileInputStream signedEmailInputStream = new FileInputStream("signed_email.eml");
            MimeMessage signedEmailMimeMessage = new MimeMessage(null, signedEmailInputStream);
            KeyStore trustStore = KeyStore.getInstance("JKS");
            trustStore.load(new FileInputStream("truststore.jks"), "changeit".toCharArray());
            PKIXParameters pkixParameters = new PKIXParameters(trustStore);
            pkixParameters.setRevocationEnabled(false);
            SignedMailValidator signedMailValidator = new SignedMailValidator(signedEmailMimeMessage, pkixParameters);
            boolean successfulValidation = true;
            for (SignerInformation signerInformation : signedMailValidator.getSignerInformationStore().getSigners()) {
                SignedMailValidator.ValidationResult signerValidationResult = signedMailValidator
                        .getValidationResult(signerInformation);
                if (!signerValidationResult.isValidSignature()) {
                    successfulValidation = false;
                    break;
                }
            }
            if (successfulValidation) {
                System.out.println("Signed email validated correctly.");
            } else {
                System.out.println("Signed email validation failed.");
            }
        }
    }
    

    Where truststore.jks should contain a CA certificate (e.g. the issuing CA) that chains to the certificate used to sign the email. Now, you can easily created this file using a software like https://keystore-explorer.org/.

    0 讨论(0)
提交回复
热议问题