Example usage for org.bouncycastle.mail.smime SMIMEException SMIMEException

List of usage examples for org.bouncycastle.mail.smime SMIMEException SMIMEException

Introduction

In this page you can find the example usage for org.bouncycastle.mail.smime SMIMEException SMIMEException.

Prototype

public SMIMEException(String name) 

Source Link

Usage

From source file:mitm.common.tools.SMIME.java

License:Open Source License

private static void sign(MimeMessage source, KeyStore keyStore, String alias, String password,
        String digestAlgo, String outFile) throws Exception {
    if (StringUtils.isEmpty(alias)) {
        throw new MissingArgumentException("alias is missing.");
    }//w ww. j a v a  2s. c  om

    KeyStore.Entry entry = keyStore.getEntry(alias, new KeyStore.PasswordProtection(password.toCharArray()));

    if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
        throw new KeyStoreException("Key is not a PrivateKeyEntry.");
    }

    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) entry;

    X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate();
    PrivateKey key = privateKeyEntry.getPrivateKey();

    if (certificate == null) {
        throw new KeyStoreException("Entry does not have a certificate.");
    }

    if (key == null) {
        throw new KeyStoreException("Entry does not have a private key.");
    }

    SMIMESigningAlgorithm signingAlgorithm;

    if (StringUtils.isNotEmpty(digestAlgo)) {
        signingAlgorithm = SMIMESigningAlgorithm.fromName(digestAlgo);

        if (signingAlgorithm == null) {
            throw new IllegalArgumentException(digestAlgo + " is not a valid digest.");
        }
    } else {
        signingAlgorithm = SMIMESigningAlgorithm.SHA1WITHRSA;
    }

    SMIMEBuilder builder = new SMIMEBuilderImpl(source);

    builder.addCertificates(certificate);
    builder.addSigner(key, certificate, signingAlgorithm);

    builder.sign(SMIMESignMode.CLEAR);

    MimeMessage signed = builder.buildMessage();

    if (signed == null) {
        throw new SMIMEException("Message could not be signed");
    }

    MailUtils.writeMessage(signed, new File(outFile));
}