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:com.vmware.admiral.auth.lightwave.pc.X509CertificateHelper.java

public X509Certificate getX509CertificateFromBase64(String base64Cert) throws CertificateException {
    byte[] sslTrustBytes = base64Cert.getBytes();
    InputStream is = new ByteArrayInputStream(Base64.decodeBase64(sslTrustBytes));

    CertificateFactory cf = CertificateFactory.getInstance("X509");

    return (X509Certificate) cf.generateCertificate(is);
}

From source file:org.commonjava.util.jhttpc.INTERNAL.util.SSLUtils.java

public static KeyStore decodePEMTrustStore(final String pemContent, final String aliasPrefix)
        throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
    Logger logger = LoggerFactory.getLogger(SSLUtils.class);

    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);/*from  w  w w.ja  va  2  s.  c  o m*/

    final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

    final List<String> lines = readLines(pemContent);

    final StringBuilder current = new StringBuilder();
    final List<String> entries = new ArrayList<String>();
    for (String line : lines) {
        if (line == null) {
            continue;
        }

        if (line.startsWith("-----BEGIN")) {
            current.setLength(0);
        } else if (line.startsWith("-----END")) {
            entries.add(current.toString());
        } else {
            current.append(line);
        }
    }

    logger.trace("Found {} entries to decode.", entries.size());

    int i = 0;
    for (final String entry : entries) {
        logger.trace("Decoding certificate info from:\n\n{}\n\n", entry);
        final byte[] data = decodeBase64(entry);

        final Certificate c = certFactory.generateCertificate(new ByteArrayInputStream(data));
        X509Certificate cert = (X509Certificate) c;

        Set<String> aliases = new HashSet<String>();
        if (i < 1) {
            aliases.add(aliasPrefix);
        } else {
            aliases.add(aliasPrefix + i);
        }

        extractAliases(cert, aliases);

        KeyStore.TrustedCertificateEntry ksEntry = new KeyStore.TrustedCertificateEntry(cert);
        for (String alias : aliases) {
            ks.setEntry(alias, ksEntry, null);
            logger.trace("Storing trusted cert under alias: {}\n  with DN: {}", alias,
                    cert.getSubjectDN().getName());
        }

        logger.trace("Certificate added.");

        i++;
    }

    return ks;
}

From source file:com.formkiq.core.service.propertystore.PropertyStoreDatabase.java

@Override
public Optional<Certificate> retrieveCertificate() throws CertificateException {

    Optional<Certificate> result = Optional.empty();
    String certstring = this.propertyService.getProperty(null, CERTIFICATE_KEY);

    if (!isEmpty(certstring)) {

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        result = Optional.of(cf.generateCertificate(new ByteArrayInputStream(Strings.getBytes(certstring))));
    }//  w  w w  .  ja  va  2 s .co  m

    return result;
}

From source file:org.authme.android.util.AuthMeHttpClient.java

private SSLSocketFactory newSslSocketFactory() {
    try {/*from   www  .j  a v  a  2s.c  o  m*/
        // Get an instance of the Bouncy Castle KeyStore format
        KeyStore trusted = KeyStore.getInstance("BKS");

        // Could probably load the main keystore and then append, but this works
        trusted.load(null, null);
        InputStream is = context.getResources().openRawResource(R.raw.cacert_root);
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
        Certificate certificate = certificateFactory.generateCertificate(is);
        trusted.setCertificateEntry("CACertRoot", certificate);

        // Now continue on using this keystore

        SSLSocketFactory sf = new SSLSocketFactory(trusted);
        // Hostname verification from certificate
        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
        sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        return sf;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

From source file:org.waveprotocol.wave.crypto.WaveSignerFactoryTest.java

private SignerInfo getSignerInfo() throws Exception {
    CertificateFactory fac = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) fac
            .generateCertificate(new ByteArrayInputStream(CERTIFICATE.getBytes()));

    return new SignerInfo(HashAlgorithm.SHA256, ImmutableList.of(cert), "example.com");
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

/**
 * Extracts certificates from PEM contents
 * /* w ww . ja v a 2  s  .c om*/
 * @throws CertificateException
 * @throws IOException
 */
private static List<X509Certificate> extractCertificatesFromPemContents(String pemContents)
        throws CertificateException, IOException {
    Matcher matcher = _certificate.matcher(pemContents);
    if (!matcher.find()) {
        throw new IllegalArgumentException("No certificate found in PEM contents.");
    }

    List<X509Certificate> result = new ArrayList<X509Certificate>();
    int offset = 0;
    while (true) {
        if (!matcher.find(offset)) {
            break;
        }
        byte[] certBytes = _base64.decode(matcher.group(1));
        ByteArrayInputStream certStream = new ByteArrayInputStream(certBytes);
        CertificateFactory certificateFactory = CertificateFactory.getInstance(X509);
        X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(certStream);
        certStream.close();

        result.add(x509Certificate);
        offset = matcher.end();
    }

    return result;
}

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

/**
 * The CRL of the Entrust Demo ECC CA does not exist online.
 * /*from w  w  w  . ja  va  2  s.  c o m*/
 * @throws Exception
 */
@Test
public void testEntrustDemoECCPKI() throws Exception {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate rootCertificate = (X509Certificate) certificateFactory
            .generateCertificate(ECCTest.class.getResourceAsStream("/ecc/root.cer"));
    LOG.debug("Root CA: " + rootCertificate);

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(ECCTest.class.getResourceAsStream("/ecc/www.e-contract.be.p12"), "EntrustSSL".toCharArray());

    String alias = keyStore.aliases().nextElement();
    Certificate[] certificates = keyStore.getCertificateChain(alias);
    for (Certificate certificate : certificates) {
        LOG.debug("Certificate: " + certificate);
    }

    MemoryCertificateRepository repository = new MemoryCertificateRepository();
    repository.addTrustPoint(rootCertificate);

    TrustValidator trustValidator = new TrustValidator(repository);
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator();
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator);

    trustValidator.isTrusted(certificates);
}

From source file:org.wso2.carbon.identity.application.common.util.IdentityApplicationManagementUtil.java

/**
 * Generate thumbprint of certificate/*from   w  w  w .ja  va 2 s  .  c  o m*/
 *
 * @param encodedCert Base64 encoded certificate
 * @return Decoded <code>Certificate</code>
 * @throws java.security.cert.CertificateException Error when decoding certificate
 */
public static Certificate decodeCertificate(String encodedCert) throws CertificateException {

    if (encodedCert != null) {
        byte[] bytes = Base64.decode(encodedCert);
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(bytes));
        return cert;
    } else {
        String errorMsg = "Invalid encoded certificate: \'NULL\'";
        log.debug(errorMsg);
        throw new IllegalArgumentException(errorMsg);
    }
}

From source file:org.wso2.carbon.identity.application.common.util.IdentityApplicationManagementUtil.java

/**
 * @param encodedCert/*from w  w  w. ja va  2s .c om*/
 * @return
 * @throws CertificateException
 */
public static CertData getCertData(String encodedCert) throws CertificateException {

    if (encodedCert != null) {
        byte[] bytes = Base64.decode(encodedCert);
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(bytes));
        Format formatter = new SimpleDateFormat("dd/MM/yyyy");
        return fillCertData(cert, formatter);
    } else {
        String errorMsg = "Invalid encoded certificate: \'NULL\'";
        log.debug(errorMsg);
        throw new IllegalArgumentException(errorMsg);
    }
}

From source file:org.waveprotocol.wave.crypto.WaveSignerFactory.java

private X509Certificate getCertificate(InputStream stream) throws CertificateException {
    CertificateFactory factory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
    return (X509Certificate) factory.generateCertificate(stream);
}