Example usage for java.security.cert CertificateFactory generateCertificate

List of usage examples for java.security.cert CertificateFactory generateCertificate

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory generateCertificate.

Prototype

public final Certificate generateCertificate(InputStream inStream) throws CertificateException 

Source Link

Document

Generates a certificate object and initializes it with the data read from the input stream inStream .

Usage

From source file:org.apache.synapse.transport.certificatevalidation.RevocationVerificationManager.java

/**
 * @param certs array of javax.security.cert.X509Certificate[] s.
 * @return the converted array of java.security.cert.X509Certificate[] s.
 * @throws CertificateVerificationException
 *//*ww  w  .  j av a  2s .c  o  m*/
private X509Certificate[] convert(javax.security.cert.X509Certificate[] certs)
        throws CertificateVerificationException {
    X509Certificate[] certChain = new X509Certificate[certs.length];
    Throwable exceptionThrown;
    for (int i = 0; i < certs.length; i++) {
        try {
            byte[] encoded = certs[i].getEncoded();
            ByteArrayInputStream bis = new ByteArrayInputStream(encoded);
            java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory
                    .getInstance("X.509");
            certChain[i] = ((X509Certificate) cf.generateCertificate(bis));
            continue;
        } catch (java.security.cert.CertificateEncodingException e) {
            exceptionThrown = e;
        } catch (javax.security.cert.CertificateEncodingException e) {
            exceptionThrown = e;
        } catch (java.security.cert.CertificateException e) {
            exceptionThrown = e;
        }
        throw new CertificateVerificationException("Cant Convert certificates from javax to java",
                exceptionThrown);
    }
    return certChain;
}

From source file:gov.nih.nci.cacisweb.action.SecureFTPAddAction.java

@Override
public String execute() throws Exception {
    log.debug("execute() - START");
    String secureFTPPropertyFileLocation = CaCISUtil
            .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_PROPERTIES_FILE_LOCATION);
    String secureFTPKeystoreLocation = CaCISUtil.getPropertyFromPropertiesFile(secureFTPPropertyFileLocation,
            CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_TRUSTSTORE_LOCATION_PROP_NAME));
    String secureFTPKeystorePassword = CaCISUtil.getPropertyFromPropertiesFile(secureFTPPropertyFileLocation,
            CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_TRUSTSTORE_PASSWORD_PROP_NAME));
    try {//from w  w  w.ja  v a  2s . c o  m
        CaCISUtil caCISUtil = new CaCISUtil();
        KeyStore keystore = caCISUtil.getKeystore(secureFTPKeystoreLocation,
                CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, secureFTPKeystorePassword);

        if (keystore.containsAlias(secureFTPBean.getCertificateAlias())) {
            log.error(getText("secureFTPBean.duplicateKey"));
            addFieldError("secureFTPBean.certificateAlias", getText("secureFTPBean.duplicateKey"));
        }

        if (StringUtils.contains(secureFTPBean.getCertificateAlias(), "ftps")) {
            if (StringUtils.isBlank(secureFTPBean.getCertificateFileName())) {
                log.error(getText("secureFTPBean.certificateRequired"));
                addFieldError("secureFTPBean.certificateFileName",
                        getText("secureFTPBean.certificateRequired"));
                caCISUtil.releaseKeystore();
                return INPUT;
            } else {
                caCISUtil.releaseKeystore();
                FileInputStream certificateStream = new FileInputStream(secureFTPBean.getCertificate());

                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                java.security.cert.Certificate cert = cf.generateCertificate(certificateStream);
                // Add the certificate
                keystore.setCertificateEntry(secureFTPBean.getCertificateAlias(), cert);

                // Save the new keystore contents
                FileOutputStream out = new FileOutputStream(new File(secureFTPKeystoreLocation));
                keystore.store(out, secureFTPKeystorePassword.toCharArray());
                out.close();
            }
        }

        // add the new entry to FTP configuration properties file
        PropertiesConfiguration config = new PropertiesConfiguration(
                CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_CONFIG_FILE_LOCATION));
        config.setProperty(secureFTPBean.getCertificateAlias(), "");
        config.save();
    } catch (KeystoreInstantiationException kie) {
        log.error(kie.getMessage());
        addActionError(getText("exception.keystoreInstantiation"));
        return ERROR;
    } catch (CertificateException ce) {
        log.error(CaCISUtil.getStackTrace(ce));
        addActionError(getText("exception.certification"));
        return INPUT;
    }
    addActionMessage(getText("secureFTPBean.addCertificateSuccessful"));
    log.debug("execute() - END");
    return SUCCESS;
}

From source file:test.integ.be.fedict.trust.Foreigner201305Test.java

/**
 * wget --recursive -e robots=off http://certs.eid.belgium.be
 * /* w  ww  . ja va  2s . com*/
 * @throws Exception
 */
@Test
public void testAllCertificateAuthorities() throws Exception {
    File dirFile = new File("/home/fcorneli/certs/certs.eid.belgium.be");
    LOG.debug("directory: " + dirFile.getAbsolutePath());
    File[] certFiles = dirFile.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            LOG.debug(name);
            return name.endsWith("crt");
        }
    });
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    for (File certFile : certFiles) {
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(new FileInputStream(certFile));
        LOG.debug("certificate: " + certificate.getSubjectX500Principal());
        RSAPublicKey rsaPublicKey = (RSAPublicKey) certificate.getPublicKey();
        int modulusSize = rsaPublicKey.getModulus().toByteArray().length;
        LOG.debug("modulus size: " + modulusSize);
        int signatureSize = certificate.getSignature().length;
        LOG.debug("signature size: " + signatureSize);
        assertEquals(modulusSize - 1, signatureSize);
    }
    LOG.debug("total number of CAs: " + certFiles.length);
}

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

/**
 * @param certs array of javax.security.cert.X509Certificate[] s.
 * @return the converted array of java.security.cert.X509Certificate[] s.
 * @throws CertificateVerificationException
 *///from  ww w .  j ava  2s  .  co  m
private X509Certificate[] convert(javax.security.cert.X509Certificate[] certs)
        throws CertificateVerificationException {
    X509Certificate[] certChain = new X509Certificate[certs.length];
    Throwable exceptionThrown;
    for (int i = 0; i < certs.length; i++) {
        try {
            byte[] encoded = certs[i].getEncoded();
            ByteArrayInputStream bis = new ByteArrayInputStream(encoded);
            java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory
                    .getInstance("X.509");
            certChain[i] = ((X509Certificate) cf.generateCertificate(bis));
            continue;
        } catch (java.security.cert.CertificateEncodingException e) {
            exceptionThrown = e;
        } catch (javax.security.cert.CertificateEncodingException e) {
            exceptionThrown = e;
        } catch (java.security.cert.CertificateException e) {
            exceptionThrown = e;
        }
        throw new CertificateVerificationException("Cant Convert certificates from " + "javax to java",
                exceptionThrown);
    }
    return certChain;
}

From source file:org.codice.ddf.security.handler.pki.CrlCheckerTest.java

/**
 * Exctracts list of X509 certs from a given cert string
 *
 * @param certString Certificate string//from w  ww.j  ava2 s  .c  o m
 * @return List of X509 certs in the string
 */
private X509Certificate[] extractX509CertsFromString(String certString) throws CertificateException {
    InputStream stream = new ByteArrayInputStream(Base64.decodeBase64(certString.getBytes()));
    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) factory.generateCertificate(stream);
    X509Certificate[] certs = new X509Certificate[1];
    certs[0] = cert;

    return certs;
}

From source file:edu.washington.iam.tools.IamConnectionManager.java

protected X509Certificate readCertificate(String filename) {
    FileInputStream file;//  w  w  w  .ja v a  2  s  . co  m
    X509Certificate cert;
    try {
        file = new FileInputStream(filename);
    } catch (IOException e) {
        log.error("ldap source bad cert file: " + e);
        return null;
    }
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(file);
    } catch (CertificateException e) {
        log.error("ldap source bad cert: " + e);
        return null;
    }
    return cert;
}

From source file:org.apache.ws.security.components.crypto.CryptoProviderTest.java

/**
 * Test loading a certificate using BouncyCastle, and using it to encrypt a message, but
 * decrypt the message using the Java Keystore provider
 *//*ww  w .  jav a  2  s . c o  m*/
@org.junit.Test
public void testInterop() throws Exception {
    // 
    // This cert corresponds to the cert in wss86.keystore
    // Extracted with:
    // keytool -export -rfc -keystore wss86.keystore -alias wss86 -file wss86.cer
    //
    byte[] certBytes = org.apache.ws.security.util.Base64
            .decode("MIICfDCCAeUCBEnHoGMwDQYJKoZIhvcNAQEEBQAwgYQxCzAJBgNVBAYTAkRFMQ8wDQYDVQQIEwZC"
                    + "YXllcm4xDzANBgNVBAcTBk11bmljaDEPMA0GA1UEChMGQXBhY2hlMQ4wDAYDVQQLEwVXU1M0SjEP"
                    + "MA0GA1UEAxMGV2VybmVyMSEwHwYJKoZIhvcNAQkBFhJXZXJuZXJAZXhhbXBsZS5jb20wHhcNMDkw"
                    + "MzIzMTQ0NDUxWhcNMTkwMzIxMTQ0NDUxWjCBhDELMAkGA1UEBhMCREUxDzANBgNVBAgTBkJheWVy"
                    + "bjEPMA0GA1UEBxMGTXVuaWNoMQ8wDQYDVQQKEwZBcGFjaGUxDjAMBgNVBAsTBVdTUzRKMQ8wDQYD"
                    + "VQQDEwZXZXJuZXIxITAfBgkqhkiG9w0BCQEWEldlcm5lckBleGFtcGxlLmNvbTCBnzANBgkqhkiG"
                    + "9w0BAQEFAAOBjQAwgYkCgYEA3uRplw7q8y/sIR541uCrlbIMzJHXCRU3nQreGNr6dM49/LxHYffQ"
                    + "Ex99chQh+wR6fwArFlziDRNnqslOy8zKMfGbaBaR41ZZrxvkSsIwzOhD6yAPgKVQL2vTmJAbdZ35"
                    + "GwcOW8oe7l+NV9qmv7yrr5OhqDhFh36WhgjVLiwmP/cCAwEAATANBgkqhkiG9w0BAQQFAAOBgQBP"
                    + "PnR2BYn7DKn/SkU8XTgf9g2NoYcMyvQOB+Uo25/QzDdMk6HKmHl0+7mh7RAtXcBz2YqC3WbQW5U3"
                    + "KmOH6fVxB8hw6xalBjs2YpnBx4gaHAws35KlAfkGVVe5wqnrI7ER7RBYO/7Gr7uCUq11QrGyEG8/"
                    + "yIXktaFLxgD2R4hpfA==");
    CertificateFactory factory = CertificateFactory.getInstance("X.509", "BC");
    X509Certificate cert = (X509Certificate) factory
            .generateCertificate(new java.io.ByteArrayInputStream(certBytes));

    WSSecEncrypt encrypt = new WSSecEncrypt();
    encrypt.setUseThisCert(cert);
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Document encryptedDoc = encrypt.build(doc, crypto, secHeader);

    if (LOG.isDebugEnabled()) {
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
        LOG.debug(outputString);
    }
    verify(encryptedDoc);

}

From source file:org.apache.ws.security.components.crypto.CryptoProviderTest.java

/**
 * Test loading a certificate using BouncyCastle, and using it to encrypt a message, but
 * decrypt the message using the Java Keystore provider. In this case though the cert doesn't
 * correspond with the cert in wss86.keystore.
 *//*from  w  ww . j  av a  2  s.  c  o m*/
@org.junit.Test
public void testBadInterop() throws Exception {
    byte[] certBytes = org.apache.ws.security.util.Base64
            .decode("MIIDNDCCAp2gAwIBAgIBEDANBgkqhkiG9w0BAQQFADBmMQswCQYDVQQGEwJERTEPMA0GA1UECBMG"
                    + "QmF5ZXJuMQ8wDQYDVQQHEwZNdW5pY2gxDTALBgNVBAoTBEhvbWUxFTATBgNVBAsTDEFwYWNoZSBX"
                    + "U1M0SjEPMA0GA1UEAxMGV2VybmVyMB4XDTA4MDQwNDE5MzIxOFoXDTEwMDQwNDE5MzIxOFowYTEL"
                    + "MAkGA1UEBhMCREUxDzANBgNVBAgTBkJheWVybjEPMA0GA1UEBxMGTXVuaWNoMQ8wDQYDVQQKEwZB"
                    + "cGFjaGUxDjAMBgNVBAsTBVdTUzRKMQ8wDQYDVQQDEwZXZXJuZXIwgZ8wDQYJKoZIhvcNAQEBBQAD"
                    + "gY0AMIGJAoGBAINlL3/k0H/zvknpBtLo8jzXwx/IJU/CGSv6MsqJZ2fyZ6kpLlXCuSBUZ/tfkdxp"
                    + "uzhYq/Sc7A8csIk9gDf9RUbrhK0qKw0VP6DoCIJjS5IeN+NeJkx8YjmzLPmZqLYbNPXr/hy8CRrR"
                    + "6CqLTTSkBwoEJ+cDkfZrdH2/bND0FEIZAgMBAAGjgfYwgfMwCQYDVR0TBAIwADAsBglghkgBhvhC"
                    + "AQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFFSZXv0I5bG7XPEw"
                    + "jylwG3lmZGdiMIGYBgNVHSMEgZAwgY2AFL/FsHHolGIMacU1TZW/88Bd2EL6oWqkaDBmMQswCQYD"
                    + "VQQGEwJERTEPMA0GA1UECBMGQmF5ZXJuMQ8wDQYDVQQHEwZNdW5pY2gxDTALBgNVBAoTBEhvbWUx"
                    + "FTATBgNVBAsTDEFwYWNoZSBXU1M0SjEPMA0GA1UEAxMGV2VybmVyggkAuBIOAWJ19mwwDQYJKoZI"
                    + "hvcNAQEEBQADgYEAUiUh/wORVcQYXxIh13h3w2Btg6Kj2g6V6YO0Utc/gEYWwT310C2OuroKAwwo"
                    + "HapMIIWiJRclIAiA8Hnb0Sv/puuHYD4G4NWFdiVjRord90eZJe40NMGruRmlqIRIGGKCv+wv3E6U"
                    + "x1cWW862f5H9Eyrcocke2P+3GNAGy83vghA=");
    CertificateFactory factory = CertificateFactory.getInstance("X.509", "BC");
    X509Certificate cert = (X509Certificate) factory
            .generateCertificate(new java.io.ByteArrayInputStream(certBytes));

    WSSecEncrypt encrypt = new WSSecEncrypt();
    encrypt.setUseThisCert(cert);
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Document encryptedDoc = encrypt.build(doc, crypto, secHeader);

    if (LOG.isDebugEnabled()) {
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
        LOG.debug(outputString);
    }
    try {
        verify(encryptedDoc);
        fail("Failure expected on encryption with a key that does not exist in the keystore");
    } catch (Exception ex) {
        // expected
    }

}

From source file:com.sk89q.mclauncher.security.X509KeyStore.java

/**
 * Add root certificates from an input stream.
 * //w  w  w  .  j a  v  a2  s .c om
 * @param in
 *            input
 * @throws CertificateException
 *             on error
 * @throws IOException
 *             on I/O error
 */
public void addRootCertificates(InputStream in) throws CertificateException, IOException {
    try {
        BufferedInputStream bufferedIn = new BufferedInputStream(in);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        while (bufferedIn.available() > 0) {
            Certificate cert = cf.generateCertificate(bufferedIn);
            addRootCertificate((X509Certificate) cert);
        }
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:com.sk89q.mclauncher.security.X509KeyStore.java

/**
 * Add root certificates from an input stream.
 * /*  w  w  w.  j a  v  a2 s  . c om*/
 * @param in
 *            input
 * @throws CertificateException
 *             on error
 * @throws IOException
 *             on I/O error
 */
public void addIntermediateCertificate(InputStream in) throws CertificateException, IOException {
    try {
        BufferedInputStream bufferedIn = new BufferedInputStream(in);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        while (bufferedIn.available() > 0) {
            Certificate cert = cf.generateCertificate(bufferedIn);
            addIntermediateCertificate((X509Certificate) cert);
        }
    } finally {
        IOUtils.closeQuietly(in);
    }
}