Java Code Examples for java.security.cert.CertificateFactory#generateCertificates()

The following examples show how to use java.security.cert.CertificateFactory#generateCertificates() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BlacklistedCertsConverter.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        System.out.println("Usage: java BlacklistedCertsConverter SHA-256" +
                " < blacklisted.certs.pem > blacklisted.certs");
        System.exit(1);
    }
    String mdAlg = args[0];
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Collection<? extends Certificate> certs
            = cf.generateCertificates(System.in);
    System.out.println("Algorithm=" + mdAlg);
    for (Certificate cert: certs) {
        System.out.println(
                getCertificateFingerPrint(mdAlg, (X509Certificate)cert));
    }
}
 
Example 2
Source File: HttpClientProperties.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
public X509Certificate[] getTrustedX509CertificatesForTrustManager() {
	try {
		CertificateFactory certificateFactory = CertificateFactory
				.getInstance("X.509");
		ArrayList<Certificate> allCerts = new ArrayList<>();
		for (String trustedCert : getTrustedX509Certificates()) {
			try {
				URL url = ResourceUtils.getURL(trustedCert);
				Collection<? extends Certificate> certs = certificateFactory
						.generateCertificates(url.openStream());
				allCerts.addAll(certs);
			}
			catch (IOException e) {
				throw new WebServerException(
						"Could not load certificate '" + trustedCert + "'", e);
			}
		}
		return allCerts.toArray(new X509Certificate[allCerts.size()]);
	}
	catch (CertificateException e1) {
		throw new WebServerException("Could not load CertificateFactory X.509",
				e1);
	}
}
 
Example 3
Source File: BlacklistedCertsConverter.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        System.out.println("Usage: java BlacklistedCertsConverter SHA-256" +
                " < blacklisted.certs.pem > blacklisted.certs");
        System.exit(1);
    }
    String mdAlg = args[0];
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Collection<? extends Certificate> certs
            = cf.generateCertificates(System.in);
    System.out.println("Algorithm=" + mdAlg);
    for (Certificate cert: certs) {
        System.out.println(
                getCertificateFingerPrint(mdAlg, (X509Certificate)cert));
    }
}
 
Example 4
Source File: Archive.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * TBD improve this.
 */
private void loadCertificates() throws IOException {
  final File f = new File(getPath() + CERTS_SUFFIX);
  if (f.canRead()) {
    try {
      final CertificateFactory cf = CertificateFactory.getInstance("X.509");
      final FileInputStream fis = new FileInputStream(f);
      final Collection<? extends Certificate> c = cf.generateCertificates(fis);
      // TBD, check if order is preserved
      if (c.size() > 0) {
        certs = new Certificate[c.size()];
        certs = c.toArray(certs);
      }
    } catch (final CertificateException e) {
      ba.frameworkWarning(e);
    }
  }
  // TODO, load certificates from both trusted and untrusted storage!?
}
 
Example 5
Source File: BlacklistedCertsConverter.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        System.out.println("Usage: java BlacklistedCertsConverter SHA-256" +
                " < blacklisted.certs.pem > blacklisted.certs");
        System.exit(1);
    }
    String mdAlg = args[0];
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Collection<? extends Certificate> certs
            = cf.generateCertificates(System.in);
    System.out.println("Algorithm=" + mdAlg);
    for (Certificate cert: certs) {
        System.out.println(
                getCertificateFingerPrint(mdAlg, (X509Certificate)cert));
    }
}
 
Example 6
Source File: TLSSocketFactory.java    From braintree_android with MIT License 5 votes vote down vote up
/**
 * @see <a href="http://developer.android.com/training/articles/security-ssl.html#UnknownCa">Android Documentation</a>
 */
public TLSSocketFactory(InputStream certificateStream) throws SSLException {
    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);

        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        Collection<? extends Certificate> certificates =
                cf.generateCertificates(certificateStream);
        for (Certificate cert : certificates) {
            if (cert instanceof X509Certificate) {
                String subject = ((X509Certificate) cert).getSubjectDN().getName();
                keyStore.setCertificateEntry(subject, cert);
            }
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);
        mInternalSSLSocketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        throw new SSLException(e.getMessage());
    } finally {
        try {
            certificateStream.close();
        } catch (IOException | NullPointerException ignored) {}
    }
}
 
Example 7
Source File: GenerateCertificatesEmptyCollection.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    /*
     * create an empty SignedData content type in ASN.1
     * as defined in PKCS#7
     */
    byte[] b = { 0x30, 0x23,
                 /* contentInfo ::= signedData */
                 0x06, 0x09, 0x2A, (byte)0x86, 0x48,
                 (byte)0x86, (byte)0xF7, 0x0D,
                 0x01, 0x07, 0x02,
                 0x00, 0x16,
                 0x30, 0x14,                /* SignedData */
                 0x02, 0x01, 0x01,          /* version */
                 0x31, 0x00,                /* digestAlgorithms */
                 0x30, 0x0B,                /* contentInfo ::= data */
                 0x06, 0x09, 0x2A, (byte)0x86, 0x48,
                 (byte)0x86, (byte)0xF7, 0x0D,
                 0x01, 0x07, 0x01,
                 /* certificates are absent */
                 0x31, 0x00                 /* signerInfos */
               };

    CertificateFactory cf = CertificateFactory.getInstance( "X509", "SUN");
    Collection c = cf.generateCertificates( new ByteArrayInputStream(b));
    if (!c.isEmpty())
        throw new Exception("CertificateFactory.generateCertificates() "
            + "did not return an empty Collection");
}
 
Example 8
Source File: GenerateCertificatesEmptyCollection.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    /*
     * create an empty SignedData content type in ASN.1
     * as defined in PKCS#7
     */
    byte[] b = { 0x30, 0x23,
                 /* contentInfo ::= signedData */
                 0x06, 0x09, 0x2A, (byte)0x86, 0x48,
                 (byte)0x86, (byte)0xF7, 0x0D,
                 0x01, 0x07, 0x02,
                 0x00, 0x16,
                 0x30, 0x14,                /* SignedData */
                 0x02, 0x01, 0x01,          /* version */
                 0x31, 0x00,                /* digestAlgorithms */
                 0x30, 0x0B,                /* contentInfo ::= data */
                 0x06, 0x09, 0x2A, (byte)0x86, 0x48,
                 (byte)0x86, (byte)0xF7, 0x0D,
                 0x01, 0x07, 0x01,
                 /* certificates are absent */
                 0x31, 0x00                 /* signerInfos */
               };

    CertificateFactory cf = CertificateFactory.getInstance( "X509", "SUN");
    Collection c = cf.generateCertificates( new ByteArrayInputStream(b));
    if (!c.isEmpty())
        throw new Exception("CertificateFactory.generateCertificates() "
            + "did not return an empty Collection");
}
 
Example 9
Source File: CertificateStreamProvider.java    From openshift-ping with Apache License 2.0 5 votes vote down vote up
static TrustManager[] configureCaCert(String caCertFile) throws Exception {
    if (caCertFile != null) {
        try {
            InputStream pemInputStream = openFile(caCertFile);
            CertificateFactory certFactory = CertificateFactory.getInstance("X509");

            KeyStore trustStore = KeyStore.getInstance("JKS");
            trustStore.load(null);

            Collection<? extends Certificate> certificates = certFactory.generateCertificates(pemInputStream);
            for (Certificate c : certificates) {
                X509Certificate certificate = (X509Certificate) c;
                String alias = certificate.getSubjectX500Principal().getName();
                trustStore.setCertificateEntry(alias, certificate);
            }

            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(trustStore);

            return trustManagerFactory.getTrustManagers();
        } catch (Exception e) {
            log.log(Level.SEVERE, "Could not create trust manager for " + caCertFile, e);
            throw e;
        }
    } else {
        if (log.isLoggable(Level.WARNING)) {
            log.log(Level.WARNING, "ca cert file undefined");
        }
        return InsecureStreamProvider.INSECURE_TRUST_MANAGERS;
    }
}
 
Example 10
Source File: ClientLoader.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static Certificate[] getJagexCertificateChain()
{
	try
	{
		CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
		Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(ClientLoader.class.getResourceAsStream("jagex.crt"));
		return certificates.toArray(new Certificate[0]);
	}
	catch (CertificateException e)
	{
		throw new RuntimeException("Unable to parse pinned certificates", e);
	}
}
 
Example 11
Source File: CertificateManager.java    From jadx with Apache License 2.0 5 votes vote down vote up
static Collection<? extends Certificate> readCertificates(InputStream in) {
	try {
		CertificateFactory cf = CertificateFactory.getInstance(CERTIFICATE_TYPE_NAME);
		return cf.generateCertificates(in);
	} catch (Exception e) {
		LOG.error("Certificate read error", e);
	}
	return Collections.emptyList();
}
 
Example 12
Source File: CertReplace.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static X509Certificate[] createPath(String chain) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    List list = new ArrayList();
    for (Certificate c: cf.generateCertificates(
            new FileInputStream(chain))) {
        list.add((X509Certificate)c);
    }
    return (X509Certificate[]) list.toArray(new X509Certificate[0]);
}
 
Example 13
Source File: GenerateCertificatesEmptyCollection.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    /*
     * create an empty SignedData content type in ASN.1
     * as defined in PKCS#7
     */
    byte[] b = { 0x30, 0x23,
                 /* contentInfo ::= signedData */
                 0x06, 0x09, 0x2A, (byte)0x86, 0x48,
                 (byte)0x86, (byte)0xF7, 0x0D,
                 0x01, 0x07, 0x02,
                 0x00, 0x16,
                 0x30, 0x14,                /* SignedData */
                 0x02, 0x01, 0x01,          /* version */
                 0x31, 0x00,                /* digestAlgorithms */
                 0x30, 0x0B,                /* contentInfo ::= data */
                 0x06, 0x09, 0x2A, (byte)0x86, 0x48,
                 (byte)0x86, (byte)0xF7, 0x0D,
                 0x01, 0x07, 0x01,
                 /* certificates are absent */
                 0x31, 0x00                 /* signerInfos */
               };

    CertificateFactory cf = CertificateFactory.getInstance( "X509", "SUN");
    Collection c = cf.generateCertificates( new ByteArrayInputStream(b));
    if (!c.isEmpty())
        throw new Exception("CertificateFactory.generateCertificates() "
            + "did not return an empty Collection");
}
 
Example 14
Source File: AbstractCBLWebSocket.java    From couchbase-lite-java with Apache License 2.0 5 votes vote down vote up
private X509TrustManager trustManagerForCertificates(InputStream in) throws GeneralSecurityException {
    final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    final Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
    if (certificates.isEmpty()) {
        throw new IllegalArgumentException("expected non-empty set of trusted certificates");
    }

    // Put the certificates a key store.
    final char[] password = "umwxnikwxx".toCharArray(); // Any password will work.
    final KeyStore keyStore = newEmptyKeyStore(password);
    int index = 0;
    for (Certificate certificate : certificates) {
        final String certificateAlias = Integer.toString(index++);
        keyStore.setCertificateEntry(certificateAlias, certificate);
    }

    // Use it to build an X509 trust manager.
    final KeyManagerFactory keyManagerFactory
        = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password);
    final TrustManagerFactory trustManagerFactory
        = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    final TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
        throw new IllegalStateException("Unexpected default trust managers:"
            + Arrays.toString(trustManagers));
    }
    return (X509TrustManager) trustManagers[0];
}
 
Example 15
Source File: Certificate.java    From apkfile with Apache License 2.0 5 votes vote down vote up
private void loadCertificates(byte[] certificateBytes) throws IOException, NoSuchAlgorithmException, CertificateException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Collection<X509Certificate> certificates = (Collection<X509Certificate>) cf.generateCertificates(new ByteArrayInputStream(certificateBytes));
    for (X509Certificate certificate : certificates) {
        byte[] publicKeyHash = Utils.sha1(new ByteArrayInputStream(certificate.getPublicKey().getEncoded()));
        byte[] signatureHash = Utils.sha1(new ByteArrayInputStream(certificate.getSignature()));
        String subjectPrincipal = certificate.getSubjectX500Principal().getName();
        String issuerPrincipal = certificate.getIssuerX500Principal().getName();
        String publicKeyHashString = Utils.bytesToHex(publicKeyHash);
        String signatureHashString = Utils.bytesToHex(signatureHash);
        ApkCertificate apkCertificate = new ApkCertificate(subjectPrincipal, issuerPrincipal, publicKeyHashString, signatureHashString);
        apkCertificates.add(apkCertificate);
    }
}
 
Example 16
Source File: CertReplace.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static X509Certificate[] createPath(String chain) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    List list = new ArrayList();
    for (Certificate c: cf.generateCertificates(
            new FileInputStream(chain))) {
        list.add((X509Certificate)c);
    }
    return (X509Certificate[]) list.toArray(new X509Certificate[0]);
}
 
Example 17
Source File: GenerateCertificatesEmptyCollection.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    /*
     * create an empty SignedData content type in ASN.1
     * as defined in PKCS#7
     */
    byte[] b = { 0x30, 0x23,
                 /* contentInfo ::= signedData */
                 0x06, 0x09, 0x2A, (byte)0x86, 0x48,
                 (byte)0x86, (byte)0xF7, 0x0D,
                 0x01, 0x07, 0x02,
                 0x00, 0x16,
                 0x30, 0x14,                /* SignedData */
                 0x02, 0x01, 0x01,          /* version */
                 0x31, 0x00,                /* digestAlgorithms */
                 0x30, 0x0B,                /* contentInfo ::= data */
                 0x06, 0x09, 0x2A, (byte)0x86, 0x48,
                 (byte)0x86, (byte)0xF7, 0x0D,
                 0x01, 0x07, 0x01,
                 /* certificates are absent */
                 0x31, 0x00                 /* signerInfos */
               };

    CertificateFactory cf = CertificateFactory.getInstance( "X509", "SUN");
    Collection c = cf.generateCertificates( new ByteArrayInputStream(b));
    if (!c.isEmpty())
        throw new Exception("CertificateFactory.generateCertificates() "
            + "did not return an empty Collection");
}
 
Example 18
Source File: GenerateCertificatesEmptyCollection.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    /*
     * create an empty SignedData content type in ASN.1
     * as defined in PKCS#7
     */
    byte[] b = { 0x30, 0x23,
                 /* contentInfo ::= signedData */
                 0x06, 0x09, 0x2A, (byte)0x86, 0x48,
                 (byte)0x86, (byte)0xF7, 0x0D,
                 0x01, 0x07, 0x02,
                 0x00, 0x16,
                 0x30, 0x14,                /* SignedData */
                 0x02, 0x01, 0x01,          /* version */
                 0x31, 0x00,                /* digestAlgorithms */
                 0x30, 0x0B,                /* contentInfo ::= data */
                 0x06, 0x09, 0x2A, (byte)0x86, 0x48,
                 (byte)0x86, (byte)0xF7, 0x0D,
                 0x01, 0x07, 0x01,
                 /* certificates are absent */
                 0x31, 0x00                 /* signerInfos */
               };

    CertificateFactory cf = CertificateFactory.getInstance( "X509", "SUN");
    Collection c = cf.generateCertificates( new ByteArrayInputStream(b));
    if (!c.isEmpty())
        throw new Exception("CertificateFactory.generateCertificates() "
            + "did not return an empty Collection");
}
 
Example 19
Source File: BlacklistedCertsConverter.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] pattern = "#! java BlacklistedCertsConverter ".getBytes();
        String mdAlg = "";

        for (int i=0; ; i++) {
            int n = System.in.read();
            if (n < 0) {
                throw new Exception("Unexpected EOF");
            }
            if (i < pattern.length) {
                if (n != pattern[i]) {
                    throw new Exception("The first line must start with \""
                            + new String(pattern) + "\"");
                }
            } else if (i < pattern.length + 100) {
                if (n < 32) {
                    break;
                } else {
                    mdAlg = mdAlg + String.format("%c", n);
                }
            }
        }

        mdAlg = mdAlg.trim();
        System.out.println("Algorithm=" + mdAlg);

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Collection<? extends Certificate> certs
                = cf.generateCertificates(System.in);

        // Output sorted so that it's easy to locate an entry.
        Set<String> fingerprints = new TreeSet<>();
        for (Certificate cert: certs) {
            fingerprints.add(
                    getCertificateFingerPrint(mdAlg, (X509Certificate)cert));
        }

        for (String s: fingerprints) {
            System.out.println(s);
        }
    }
 
Example 20
Source File: OpenIDConnectAuthenticator.java    From java with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, Object> refresh(Map<String, Object> config) {
  String issuer = (String) config.get(OIDC_ISSUER);
  String clientId = (String) config.get(OIDC_CLIENT_ID);
  String refreshToken = (String) config.get(OIDC_REFRESH_TOKEN);
  String clientSecret = (String) config.getOrDefault(OIDC_CLIENT_SECRET, "");
  String idpCert = (String) config.get(OIDC_IDP_CERT_DATA);

  SSLContext sslContext = null;

  if (idpCert != null) {
    // fist, lets get the pem
    String pemCert = new String(Base64.getDecoder().decode(idpCert));

    // next lets get a cert object
    // need an alias name to store the certificate in a keystore.  Also
    // java keystores need passwords. this value is as good as any as
    // there isn't anything actually secret being stored.
    String alias = "doenotmatter";
    KeyStore ks;

    try {
      ks = java.security.KeyStore.getInstance("PKCS12");
      ks.load(null, alias.toCharArray());
      ByteArrayInputStream bais = new ByteArrayInputStream(pemCert.getBytes("UTF-8"));
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      Collection<? extends java.security.cert.Certificate> c = cf.generateCertificates(bais);

      int j = 0;
      for (java.security.cert.Certificate certificate : c) {
        ks.setCertificateEntry(alias + "-" + j, certificate);
        j++;
      }

      TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
      tmf.init(ks);

      // TODO would be good to make this more dyanamic.  Doesn't seem like
      // a good way to do this.
      sslContext = SSLContext.getInstance("TLSv1.2");
      sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());

    } catch (KeyStoreException
        | NoSuchAlgorithmException
        | CertificateException
        | IOException
        | KeyManagementException e) {
      throw new RuntimeException("Could not import idp certificate", e);
    }
  }

  // check the identity provider's configuration url for a token endpoint
  String tokenURL = loadTokenURL(issuer, sslContext);

  // get the refreshed tokens
  JSONObject response =
      refreshOidcToken(clientId, refreshToken, clientSecret, sslContext, tokenURL);

  // reload the config
  config.put(OIDC_ID_TOKEN, response.get("id_token"));
  config.put(OIDC_REFRESH_TOKEN, response.get("refresh_token"));

  return config;
}