Example usage for java.security Security addProvider

List of usage examples for java.security Security addProvider

Introduction

In this page you can find the example usage for java.security Security addProvider.

Prototype

public static int addProvider(Provider provider) 

Source Link

Document

Adds a provider to the next position available.

Usage

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Send an email. Also sends it as a gmail if applicable, and does password checking.
 * @param host host of SMTP server//from  ww  w .  j  a  v  a 2  s.  c om
 * @param uName username of email account
 * @param pWord password of email account
 * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email
 * @param toEMailAddr the email addr of who this is going to
 * @param subject the Textual subject line of the email
 * @param bodyText the body text of the email (plain text???)
 * @param fileAttachment and optional file to be attached to the email
 * @return true if the msg was sent, false if not
 */
public static ErrorType sendMsg(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, final String port, final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;

    if (StringUtils.isEmpty(toEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_TO_ERR");
        return ErrorType.Error;
    }

    if (StringUtils.isEmpty(fromEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_FROM_ERR");
        return ErrorType.Error;
    }

    //if (isGmailEmail())
    //{
    //    return sendMsgAsGMail(host, userName, password, fromEMailAddr, toEMailAddr, subject, bodyText, mimeType, port, security, fileAttachment);
    //}

    Boolean fail = false;
    ArrayList<String> userAndPass = new ArrayList<String>();

    boolean isSSL = security.equals("SSL");

    String[] keys = { "mail.smtp.host", "mail.smtp.port", "mail.smtp.auth", "mail.smtp.starttls.enable",
            "mail.smtp.socketFactory.port", "mail.smtp.socketFactory.class", "mail.smtp.socketFactory.fallback",
            "mail.imap.auth.plain.disable", };
    Properties props = System.getProperties();
    for (String key : keys) {
        props.remove(key);
    }

    props.put("mail.smtp.host", host); //$NON-NLS-1$

    if (StringUtils.isNotEmpty(port) && StringUtils.isNumeric(port)) {
        props.put("mail.smtp.port", port); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        props.remove("mail.smtp.port");
    }

    if (StringUtils.isNotEmpty(security)) {
        if (security.equals("TLS")) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
            props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

        } else if (isSSL) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$

            String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            props.put("mail.smtp.socketFactory.port", port);
            props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.put("mail.smtp.socketFactory.fallback", "false");
            props.put("mail.imap.auth.plain.disable", "true");
        }
    }

    Session session = null;
    if (isSSL) {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(uName, pWord);
            }
        });

    } else {
        session = Session.getInstance(props, null);
    }

    session.setDebug(instance.isDebugging);
    if (instance.isDebugging) {
        log.debug("Host:     " + host); //$NON-NLS-1$
        log.debug("UserName: " + userName); //$NON-NLS-1$
        log.debug("Password: " + password); //$NON-NLS-1$
        log.debug("From:     " + fromEMailAddr); //$NON-NLS-1$
        log.debug("To:       " + toEMailAddr); //$NON-NLS-1$
        log.debug("Subject:  " + subject); //$NON-NLS-1$
        log.debug("Port:     " + port); //$NON-NLS-1$
        log.debug("Security: " + security); //$NON-NLS-1$
    }

    try {

        // create a message
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(fromEMailAddr));

        if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$
        {
            StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$
            InternetAddress[] address = new InternetAddress[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                String toStr = st.nextToken().trim();
                address[i++] = new InternetAddress(toStr);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            try {
                InternetAddress[] address = { new InternetAddress(toEMailAddr) };
                msg.setRecipients(Message.RecipientType.TO, address);

            } catch (javax.mail.internet.AddressException ex) {
                UIRegistry.showLocalizedError("EMailHelper.TO_ADDR_ERR", toEMailAddr);
                return ErrorType.Error;
            }
        }
        msg.setSubject(subject);

        //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\"");

        // create the second message part
        if (fileAttachment != null) {
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\"");
            //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\"");

            MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
            FileDataSource fds = new FileDataSource(fileAttachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());

            // create the Multipart and add its parts to it
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);

            // add the Multipart to the message
            msg.setContent(mp);

        } else {
            // add the Multipart to the message
            msg.setContent(bodyText, mimeType);
        }

        final int TRIES = 1;

        // set the Date: header
        msg.setSentDate(new Date());

        Exception exception = null;
        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = isSSL ? null : (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                if (isSSL) {
                    Transport.send(msg);

                } else {
                    t.connect(host, userName, password);
                    t.sendMessage(msg, msg.getAllRecipients());
                }

                fail = false;

            } catch (SendFailedException mex) {
                mex.printStackTrace();
                exception = mex;

            } catch (MessagingException mex) {
                if (mex.getCause() instanceof UnknownHostException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError("EMailHelper.UNK_HOST", host);

                } else if (mex.getCause() instanceof ConnectException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError(
                            "EMailHelper." + (StringUtils.isEmpty(port) ? "CNCT_ERR1" : "CNCT_ERR2"), port);

                } else {
                    mex.printStackTrace();
                    exception = mex;
                }

            } catch (Exception mex) {
                mex.printStackTrace();
                exception = mex;

            } finally {
                if (t != null) {
                    log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                    t.close();
                }
            }

            if (exception != null) {
                fail = true;

                instance.lastErrorMsg = exception.toString();

                //wrong username or password, get new one
                if (exception.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    UIRegistry.showLocalizedError("EMailHelper.UP_ERROR", userName);

                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) { //the user is done
                        instance.lastErrorMsg = null;
                        return ErrorType.Cancel;
                    }
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }

            }
            exception = null;

        } while (fail && cnt < TRIES);

    } catch (Exception mex) {
        //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
        instance.lastErrorMsg = mex.toString();

        mex.printStackTrace();
        Exception ex = null;
        if (mex instanceof MessagingException && (ex = ((MessagingException) mex).getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return ErrorType.Error;

    }

    if (fail) {
        return ErrorType.Error;
    } //else

    return ErrorType.OK;
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESService.java

@Override
public InputStream toBeSigned(Document document, SignatureParameters parameters) throws IOException {
    if (parameters.getSignaturePackaging() != SignaturePackaging.ENVELOPING
            && parameters.getSignaturePackaging() != SignaturePackaging.DETACHED) {
        throw new IllegalArgumentException(
                "Unsupported signature packaging " + parameters.getSignaturePackaging());
    }//from w  w w .  ja  va2s  .  c  o  m

    SignatureInterceptorProvider provider = new SignatureInterceptorProvider();
    Security.addProvider(provider);

    final String jsAlgorithm = parameters.getSignatureAlgorithm()
            .getJavaSignatureAlgorithm(parameters.getDigestAlgorithm());
    final PreComputedContentSigner contentSigner = new PreComputedContentSigner(jsAlgorithm);
    DigestCalculatorProvider digestCalculatorProvider = new BcDigestCalculatorProvider();

    CMSSignedDataGenerator generator = createCMSSignedDataGenerator(contentSigner, digestCalculatorProvider,
            parameters, getSigningProfile(parameters), false, null);

    byte[] toBeSigned = IOUtils.toByteArray(document.openStream());
    CMSProcessableByteArray content = new CMSProcessableByteArray(toBeSigned);

    try {
        boolean includeContent = true;
        if (parameters.getSignaturePackaging() == SignaturePackaging.DETACHED) {
            includeContent = false;
        }

        generator.generate(content, includeContent);
        return new ByteArrayInputStream(contentSigner.getByteOutputStream().toByteArray());
    } catch (CMSException e) {
        throw new IOException(e);
    }
}

From source file:controller.CCInstance.java

public CCInstance() {
    Security.addProvider(new BouncyCastleProvider());
}

From source file:org.apache.synapse.transport.utils.sslcert.ocsp.OCSPVerifier.java

/**
 * This method generates an OCSP Request to be sent to an OCSP endpoint.
 *
 * @param issuerCert   is the Certificate of the Issuer of the peer certificate we are interested in.
 * @param serialNumber of the peer certificate.
 * @return generated OCSP request.//www  .  j  ava2s  .  c o  m
 * @throws CertificateVerificationException
 */
private OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber)
        throws CertificateVerificationException {

    //TODO: Have to check if this is OK with synapse implementation.
    //Add provider BC
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    try {
        //  CertID structure is used to uniquely identify certificates that are the subject of
        // an OCSP request or response and has an ASN.1 definition. CertID structure is defined
        // in RFC 2560
        CertificateID id = new CertificateID(CertificateID.HASH_SHA1, issuerCert, serialNumber);

        // basic request generation with nonce
        OCSPReqGenerator generator = new OCSPReqGenerator();
        generator.addRequest(id);

        // create details for nonce extension. The nonce extension is used to bind
        // a request to a response to prevent replay attacks. As the name implies,
        // the nonce value is something that the client should only use once within a reasonably
        // small period.
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        Vector<ASN1ObjectIdentifier> objectIdentifiers = new Vector<ASN1ObjectIdentifier>();
        Vector<X509Extension> values = new Vector<X509Extension>();

        //to create the request Extension
        objectIdentifiers.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
        values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray())));
        generator.setRequestExtensions(new X509Extensions(objectIdentifiers, values));

        return generator.generate();
    } catch (OCSPException e) {
        throw new CertificateVerificationException(
                "Cannot generate OCSP Request with the " + "given certificate", e);
    }
}

From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java

@Test
public void testGetCertificateAuthnCertCredential() throws Exception {
    LOG.debug("sign");
    // operate//ww w .  j av  a2  s. c  o  m
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    Security.addProvider(new HSMProxyProvider());
    KeyStore hsmProxyKeyStore = KeyStore.getInstance("HSMProxy");

    HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter(authnPrivateKey, authnCert,
            // "https://www.e-contract.be/hsm-proxy-ws/dss",
            "http://localhost/hsm-proxy-ws/dss", new MyHSMProxyAudit());
    hsmProxyKeyStore.load(keyStoreParameter);

    Enumeration<String> aliasesEnum = hsmProxyKeyStore.aliases();
    assertNotNull(aliasesEnum);
    while (aliasesEnum.hasMoreElements()) {
        String alias = aliasesEnum.nextElement();
        LOG.debug("alias: " + alias);
        X509Certificate certificate = (X509Certificate) hsmProxyKeyStore.getCertificate(alias);
        assertNotNull(certificate);
        LOG.debug("certificate: " + certificate);
        assertTrue(hsmProxyKeyStore.containsAlias(alias));
        Certificate[] certificateChain = hsmProxyKeyStore.getCertificateChain(alias);
        assertNotNull(certificateChain);
        PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) hsmProxyKeyStore.getEntry(alias, null);
        assertNotNull(privateKeyEntry);
    }
}

From source file:net.lightbody.bmp.proxy.jetty.http.SunJsseListener.java

protected SSLServerSocketFactory createFactory() throws Exception {
    _keystore = System.getProperty(KEYSTORE_PROPERTY, _keystore);

    log.info(KEYSTORE_PROPERTY + "=" + _keystore);

    if (_password == null)
        _password = Password.getPassword(PASSWORD_PROPERTY, null, null);
    log.info(PASSWORD_PROPERTY + "=" + _password.toStarString());

    if (_keypassword == null)
        _keypassword = Password.getPassword(KEYPASSWORD_PROPERTY, null, _password.toString());
    log.info(KEYPASSWORD_PROPERTY + "=" + _keypassword.toStarString());

    KeyStore ks = null;//from  www  .j a v  a2 s  . c o  m

    log.info(KEYSTORE_TYPE_PROPERTY + "=" + _keystore_type);

    if (_keystore_provider_class != null) {
        // find provider.
        // avoid creating another instance if already installed in Security.
        java.security.Provider[] installed_providers = Security.getProviders();
        java.security.Provider myprovider = null;
        for (int i = 0; i < installed_providers.length; i++) {
            if (installed_providers[i].getClass().getName().equals(_keystore_provider_class)) {
                myprovider = installed_providers[i];
                break;
            }
        }
        if (myprovider == null) {
            // not installed yet, create instance and add it
            myprovider = (java.security.Provider) Class.forName(_keystore_provider_class).newInstance();
            Security.addProvider(myprovider);
        }
        log.info(KEYSTORE_PROVIDER_CLASS_PROPERTY + "=" + _keystore_provider_class);
        ks = KeyStore.getInstance(_keystore_type, myprovider.getName());
    } else if (_keystore_provider_name != null) {
        log.info(KEYSTORE_PROVIDER_NAME_PROPERTY + "=" + _keystore_provider_name);
        ks = KeyStore.getInstance(_keystore_type, _keystore_provider_name);
    } else {
        ks = KeyStore.getInstance(_keystore_type);
        log.info(KEYSTORE_PROVIDER_NAME_PROPERTY + "=[DEFAULT]");
    }

    ks.load(new FileInputStream(new File(_keystore)), _password.toString().toCharArray());

    KeyManagerFactory km = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
    km.init(ks, _keypassword.toString().toCharArray());
    KeyManager[] kma = km.getKeyManagers();

    TrustManagerFactory tm = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
    if (_useDefaultTrustStore) {
        tm.init((KeyStore) null);
    } else {
        tm.init(ks);
    }

    TrustManager[] tma = tm.getTrustManagers();

    SSLContext sslc = SSLContext.getInstance("SSL");
    sslc.init(kma, tma, SecureRandom.getInstance("SHA1PRNG"));

    SSLServerSocketFactory ssfc = sslc.getServerSocketFactory();
    log.info("SSLServerSocketFactory=" + ssfc);
    return ssfc;
}

From source file:crypttools.PGPCryptoBC.java

public boolean validateData(String data, String publicKey) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    File fileToVerify = File.createTempFile("temp", ".privateScrap");
    FileUtils.writeStringToFile(fileToVerify, data);

    File publicKeyFile = File.createTempFile("temp", ".publicScrap");
    // Creates an exception
    //        System.out.println(this.armoredPublicKey);
    //        String armoredKeyString = getPublicKey();
    //        System.out.println(armoredKeyString);
    FileUtils.writeStringToFile(publicKeyFile, publicKey);
    //FileUtils.writeStringToFile(publicKeyFile, new String(this.armoredPublicKey, "UTF-8"));

    try {//from   www  .  j a v  a  2s  .com
        InputStream in = PGPUtil.getDecoderStream(new FileInputStream(fileToVerify));

        PGPObjectFactory pgpObjFactory = new PGPObjectFactory(in);
        PGPCompressedData compressedData = (PGPCompressedData) pgpObjFactory.nextObject();

        //Get the signature from the file

        pgpObjFactory = new PGPObjectFactory(compressedData.getDataStream());
        PGPOnePassSignatureList onePassSignatureList = (PGPOnePassSignatureList) pgpObjFactory.nextObject();
        PGPOnePassSignature onePassSignature = onePassSignatureList.get(0);

        //Get the literal data from the file

        PGPLiteralData pgpLiteralData = (PGPLiteralData) pgpObjFactory.nextObject();
        InputStream literalDataStream = pgpLiteralData.getInputStream();

        InputStream keyIn = new FileInputStream(publicKeyFile);
        PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(keyIn));
        PGPPublicKey key = pgpRing.getPublicKey(onePassSignature.getKeyID());

        FileOutputStream literalDataOutputStream = new FileOutputStream(pgpLiteralData.getFileName());
        onePassSignature.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), key);

        int ch;
        while ((ch = literalDataStream.read()) >= 0) {
            onePassSignature.update((byte) ch);
            literalDataOutputStream.write(ch);
        }

        literalDataOutputStream.close();

        //Get the signature from the written out file

        PGPSignatureList p3 = (PGPSignatureList) pgpObjFactory.nextObject();
        PGPSignature signature = p3.get(0);

        //Verify the two signatures
        boolean valid = onePassSignature.verify(signature);
        return valid;
    } catch (Exception e) {
        System.out.println("Got an Exception: " + e.getMessage());
        return false;
        //do something clever with the exception
    } finally {
        fileToVerify.delete();
        publicKeyFile.delete();
    }
}

From source file:test.integ.be.fedict.commons.eid.client.BeIDCardTest.java

@Test
public void testPSSSignatureSHA256() throws Exception {
    final BeIDCard beIDCard = getBeIDCard();

    final byte[] toBeSigned = new byte[10];
    final SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(toBeSigned);/*w w  w  .  jav a  2 s. c  o m*/

    final X509Certificate authnCertificate = beIDCard.getAuthenticationCertificate();

    final MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    final byte[] digestValue = messageDigest.digest(toBeSigned);

    byte[] signatureValue;
    try {
        signatureValue = beIDCard.sign(digestValue, BeIDDigest.SHA_256_PSS,
                FileType.AuthentificationCertificate, false);
    } finally {
        beIDCard.close();
    }

    Security.addProvider(new BouncyCastleProvider());

    final BeIDIntegrity beIDIntegrity = new BeIDIntegrity();
    final boolean result = beIDIntegrity.verifySignature("SHA256withRSAandMGF1", signatureValue,
            authnCertificate.getPublicKey(), toBeSigned);

    assertTrue(result);
}

From source file:com.infinities.keystone4j.utils.Cms.java

@SuppressWarnings("rawtypes")
public String verifySignature(byte[] sigbytes, String signingCertFileName, String caFileName)
        throws CMSException, CertificateException, OperatorCreationException, NoSuchAlgorithmException,
        NoSuchProviderException, CertPathBuilderException, InvalidAlgorithmParameterException, IOException,
        CertificateVerificationException {
    logger.debug("signingCertFile: {}, caFile:{}", new Object[] { signingCertFileName, caFileName });
    Security.addProvider(new BouncyCastleProvider());
    X509Certificate signercert = generateCertificate(signingCertFileName);
    X509Certificate cacert = generateCertificate(caFileName);
    Set<X509Certificate> additionalCerts = new HashSet<X509Certificate>();
    additionalCerts.add(cacert);/*ww  w. jav  a  2s.  co  m*/

    CertificateVerifier.verifyCertificate(signercert, additionalCerts, true); // .validateKeyChain(signercert,
    // certs);
    if (Base64Verifier.isBase64(sigbytes)) {
        try {
            sigbytes = Base64.decode(sigbytes);
            logger.debug("Signature file is BASE64 encoded");
        } catch (Exception ioe) {
            logger.warn("Problem decoding from b64", ioe);
        }
    }

    // sigbytes = Base64.decode(sigbytes);

    // --- Use Bouncy Castle provider to verify included-content CSM/PKCS#7
    // signature ---
    ASN1InputStream in = null;
    try {
        logger.debug("sigbytes size: {}", sigbytes.length);
        in = new ASN1InputStream(new ByteArrayInputStream(sigbytes), Integer.MAX_VALUE);

        CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(in.readObject()));
        Store store = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        Collection c = signers.getSigners();
        Iterator it = c.iterator();
        int verified = 0;

        while (it.hasNext()) {
            X509Certificate cert = null;
            SignerInformation signer = (SignerInformation) it.next();
            Collection certCollection = store.getMatches(signer.getSID());
            if (certCollection.isEmpty() && signercert == null)
                continue;
            else if (signercert != null) // use a signer cert file for
                // verification, if it was
                // provided
                cert = signercert;
            else { // use the certificates included in the signature for
                   // verification
                Iterator certIt = certCollection.iterator();
                cert = (X509Certificate) certIt.next();
            }

            // if (signer.verify(new
            // JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)))
            // verified++;
        }

        if (verified == 0) {
            logger.warn(" No signers' signatures could be verified !");
        } else if (signercert != null)
            logger.info("Verified a signature using signer certificate file  {}", signingCertFileName);
        else
            logger.info("Verified a signature using a certificate in the signature data");

        CMSProcessableByteArray cpb = (CMSProcessableByteArray) s.getSignedContent();
        byte[] rawcontent = (byte[]) cpb.getContent();

        return new String(rawcontent);
    } catch (Exception ex) {
        logger.error("Couldn't verify included-content CMS signature", ex);
        throw new RuntimeException("Couldn't verify included-content CMS signature", ex);
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.appdynamics.monitors.mongo.MongoDBMonitor.java

private SSLSocketFactory getSocketFactoryFromPEM(String filePath) throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    PEMParser pemParser = new PEMParser(new FileReader(getConfigFilename(filePath)));
    pemParser.readObject();/*ww w.  j av  a 2 s .c  o m*/
    PemObject pemObject = pemParser.readPemObject();
    pemParser.close();

    X509CertificateHolder holder = new X509CertificateHolder(pemObject.getContent());
    X509Certificate bc = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder);

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", bc);

    TrustManager trustManager = TrustManagerUtils.getDefaultTrustManager(keyStore);
    SSLContext sslContext = SSLContextUtils.createSSLContext("TLS", null, trustManager);

    return sslContext.getSocketFactory();
}