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

The following examples show how to use java.security.cert.CertificateFactory#generateCertificate() . 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: NoExtensions.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static X509Certificate getUserCertificate2() throws Exception {
    // this certificate does not include any extensions
    String sCert =
        "-----BEGIN CERTIFICATE-----\n"
      + "MIIBMjCB3aADAgECAhB6225ckZVssEukPuvk1U1PMA0GCSqGSIb3DQEBBAUAMBox\n"
      + "GDAWBgNVBAMTD1Jvb3RDZXJ0aWZpY2F0ZTAeFw0wMTEwMTkxNjA5NTZaFw0wMjEw\n"
      + "MTkyMjA5NTZaMBsxGTAXBgNVBAMTEFVzZXJDZXJ0aWZpY2F0ZTIwXDANBgkqhkiG\n"
      + "9w0BAQEFAANLADBIAkEAzicGiW9aUlUoQIZnLy1l8MMV5OvA+4VJ4T/xo/PpN8Oq\n"
      + "WgZVGKeEp6JCzMlXEJk3TGLfpXL4Ytw+Ldhv0QPhLwIDAnMpMA0GCSqGSIb3DQEB\n"
      + "BAUAA0EAQmj9SFHEx66JyAps3ew4pcSS3QvfVZ/6qsNUYCG75rFGcTUPHcXKql9y\n"
      + "qBT83iNLJ//krjw5Ju0WRPg/buHSww==\n"
      + "-----END CERTIFICATE-----";
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bytes = new ByteArrayInputStream(sCert.getBytes());
    return (X509Certificate)certFactory.generateCertificate(bytes);
}
 
Example 2
Source File: CertificateAuthorityTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticateCertificateNoPrincipal() throws Exception {

    CertificateAuthority authority = new CertificateAuthority();
    authority.initialize();

    try (InputStream inStream = new FileInputStream("src/test/resources/no_cn_x509.cert")) {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);

        X509Certificate[] certs = new X509Certificate[1];
        certs[0] = cert;

        StringBuilder errMsg = new StringBuilder();
        Principal principal = authority.authenticate(certs, errMsg);
        assertNull(principal);
        assertTrue(errMsg.toString().contains("Certificate principal is empty"));
    }
}
 
Example 3
Source File: TestUtils.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an SSLSocketFactory which contains {@code certChainFile} as its only root certificate.
 *
 * @deprecated Not for public use
 */
@Deprecated
public static SSLSocketFactory newSslSocketFactoryForCa(Provider provider,
    File certChainFile) throws Exception {
  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(null, null);
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  BufferedInputStream in = new BufferedInputStream(new FileInputStream(certChainFile));
  try {
    X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
    X500Principal principal = cert.getSubjectX500Principal();
    ks.setCertificateEntry(principal.getName("RFC2253"), cert);
  } finally {
    in.close();
  }

  // Set up trust manager factory to use our key store.
  TrustManagerFactory trustManagerFactory =
      TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(ks);
  SSLContext context = SSLContext.getInstance("TLS", provider);
  context.init(null, trustManagerFactory.getTrustManagers(), null);
  return context.getSocketFactory();
}
 
Example 4
Source File: SSLKeyStoreLoader.java    From tessera with Apache License 2.0 6 votes vote down vote up
private static List<X509Certificate> getCertificates(Path certificateFile)
        throws IOException, GeneralSecurityException {

    final String certFileContent = readPemFile(certificateFile);

    final Matcher matcher = CERTIFICATE_PATTERN.matcher(certFileContent);

    List<X509Certificate> certificates = new ArrayList<>();

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

    int start = 0;
    while (matcher.find(start)) {
        byte[] buffer = decoder.decode(matcher.group(1));
        final X509Certificate certificate =
                (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(buffer));
        certificates.add(certificate);
        start = matcher.end();
    }

    if (certificates.isEmpty()) {
        throw new CertificateException("NO CERTIFICATE FOUND IN FILE");
    }

    return certificates;
}
 
Example 5
Source File: HttpResponseCache.java    From bluemix-parking-meter with MIT License 6 votes vote down vote up
private Certificate[] readCertArray(StrictLineReader reader) throws IOException {
  int length = reader.readInt();
  if (length == -1) {
    return null;
  }
  try {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    Certificate[] result = new Certificate[length];
    for (int i = 0; i < result.length; i++) {
      String line = reader.readLine();
      byte[] bytes = Base64.decode(line.getBytes("US-ASCII"));
      result[i] = certificateFactory.generateCertificate(new ByteArrayInputStream(bytes));
    }
    return result;
  } catch (CertificateException e) {
    throw new IOException(e.getMessage());
  }
}
 
Example 6
Source File: CertificateUtil.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public static KeyStore createKeyStore(String certificate, String alias) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
    final KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);
    // create client key entry
    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    final Certificate generated = factory.generateCertificate(new ByteArrayInputStream
            (getMultilineCertificate(certificate).getBytes("UTF-8")));
    keyStore.setCertificateEntry(alias, generated);
    return keyStore;
}
 
Example 7
Source File: UtilShared.java    From IDES-Data-Preparation-Java with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
public static Certificate getCert(String certfile) throws Exception {
	try {
		CertificateFactory cf = CertificateFactory.getInstance(certificateType);
	    FileInputStream fs = new FileInputStream(new File(certfile));
	    Certificate cert = cf.generateCertificate(fs);
	    fs.close();
	    return cert;
	} catch (Exception e) {
		logger.debug(e.getMessage(), e);
		throw e;
	}
}
 
Example 8
Source File: ToolCertificate2.java    From protools with Apache License 2.0 5 votes vote down vote up
/**
 * 获得Certificate
 *
 * @param certificatePath
 *         证书路径
 *
 * @return Certificate 证书
 *
 * @throws Exception
 */
private static X509Certificate getCertificate(String certificatePath) throws CertificateException, IOException {

    // 实例化证书工厂
    CertificateFactory certificateFactory = CertificateFactory.getInstance(CERT_TYPE);

    Certificate certificate;
    // 取得证书文件流
    try (FileInputStream in = new FileInputStream(certificatePath)) {
        // 生成证书
        certificate = certificateFactory.generateCertificate(in);
    }
    return (X509Certificate) certificate;
}
 
Example 9
Source File: AthenzUtilsTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsRoleCertificateServiceCertificate() throws Exception {
    try (InputStream inStream = new FileInputStream("src/test/resources/x509_altnames_singleip.cert")) {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);

        assertFalse(AthenzUtils.isRoleCertificate(cert));
    }
}
 
Example 10
Source File: ClientAuthenticatorTest.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Test public void ignoresMultipleSpiffeIds() throws Exception {
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  X509Certificate multipleSpiffeClientCert = (X509Certificate) cf.generateCertificate(
      new ByteArrayInputStream(multipleSpiffePem.getBytes(UTF_8)));
  Principal multipleSpiffePrincipal =
      new CertificatePrincipal(multipleSpiffeClientCert.getSubjectDN().toString(),
          new X509Certificate[] {multipleSpiffeClientCert});

  // Use only the (malformatted) SPIFFE IDs to retrieve a client (which should fail)
  when(clientAuthTypeConfig.useCommonName()).thenReturn(false);
  when(clientAuthTypeConfig.useSpiffeId()).thenReturn(true);

  assertThat(authenticator.authenticate(multipleSpiffePrincipal, false)).isEmpty();
  verifyNoInteractions(clientDAO);
}
 
Example 11
Source File: CertificateUtils.java    From TrustKit-Android with MIT License 5 votes vote down vote up
public static Certificate certificateFromPem(String pemCertificate) {
    pemCertificate = pemCertificate.replace("-----BEGIN CERTIFICATE-----\n", "");
    pemCertificate = pemCertificate.replace("-----END CERTIFICATE-----", "");
    InputStream is = new ByteArrayInputStream(Base64.decode(pemCertificate, Base64.DEFAULT));
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        return cf.generateCertificate(is);
    } catch (CertificateException e) {
       throw new RuntimeException("Should never happen");
    }
}
 
Example 12
Source File: Certificates.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Returns {@link SignerInfo} for the (example.com) certificate chain.
 * @throws Exception if the certificates fail to be resolved properly
 */
public static SignerInfo getExampleSignerInfo() throws Exception {
  CertificateFactory factory = CertificateFactory.getInstance("X.509");
  X509Certificate exampleCert = (X509Certificate) factory.generateCertificate(
      new ByteArrayInputStream(EXAMPLE_CERTIFICATE.getBytes()));
  return new SignerInfo(HashAlgorithm.SHA256,
      ImmutableList.of(exampleCert), EXAMPLE_DOMAIN);
}
 
Example 13
Source File: CertificateUtils.java    From nifi with Apache License 2.0 5 votes vote down vote up
private static X509Certificate formX509Certificate(byte[] encodedCertificate) throws CertificateException {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream bais = new ByteArrayInputStream(encodedCertificate);
        return (X509Certificate) cf.generateCertificate(bais);
    } catch (CertificateException e) {
        logger.error("Error converting the certificate", e);
        throw e;
    }
}
 
Example 14
Source File: Util.java    From ecosys with Apache License 2.0 5 votes vote down vote up
/**
 * load the CA and use it in the https connection
 * @param filename the CA filename
 * @return the SSL context
 */
public static SSLContext getSSLContext(String filename) throws Exception {
  try {
    // Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or ...)
    // X.509 is a standard that defines the format of public key certificates, used in TLS/SSL.
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    InputStream caInput = new BufferedInputStream(new FileInputStream(filename));
    Certificate ca = cf.generateCertificate(caInput);

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    return context;
  } catch (Exception e) {
    throw new Exception("Failed to load the CA file: " + e.getMessage(), e);
  }
}
 
Example 15
Source File: SunX509ExtendedTM.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static SSLContext getSSLContext(String trusedCertStr,
        String keyCertStr, byte[] modulus,
        byte[] privateExponent, char[] passphrase) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    ByteArrayInputStream is =
                new ByteArrayInputStream(trusedCertStr.getBytes());
    Certificate trusedCert = cf.generateCertificate(is);
    is.close();

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    ks.setCertificateEntry("RSA Export Signer", trusedCert);

    if (keyCertStr != null) {
        // generate the private key.
        RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(
                                        new BigInteger(modulus),
                                        new BigInteger(privateExponent));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        Certificate[] chain = new Certificate[2];
        chain[0] = keyCert;
        chain[1] = trusedCert;

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf =
            TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);

    TrustManager tms[] = tmf.getTrustManagers();
    if (tms == null || tms.length == 0) {
        throw new Exception("unexpected trust manager implementation");
    } else {
       if (!(tms[0] instanceof X509ExtendedTrustManager)) {
        throw new Exception("unexpected trust manager implementation: "
                            + tms[0].getClass().getCanonicalName());
       }
    }


    SSLContext ctx = SSLContext.getInstance("TLS");

    if (keyCertStr != null) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 16
Source File: ECCurvesconstraints.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
private static SSLContext generateSSLContext(boolean isClient)
        throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    ByteArrayInputStream is =
                new ByteArrayInputStream(trustedCertStr.getBytes());
    Certificate trusedCert = cf.generateCertificate(is);
    is.close();

    ks.setCertificateEntry("Export Signer", trusedCert);

    String[] certStrs = null;
    String[] keyStrs = null;
    if (isClient) {
        certStrs = clientCerts;
        keyStrs = clientKeys;
    } else {
        certStrs = serverCerts;
        keyStrs = serverKeys;
    }

    for (int i = 0; i < certStrs.length; i++) {
        // generate the private key.
        String keySpecStr = keyStrs[i];
        PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
                            Base64.getMimeDecoder().decode(keySpecStr));
        KeyFactory kf = KeyFactory.getInstance("EC");
        ECPrivateKey priKey =
                (ECPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        String keyCertStr = certStrs[i];
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        Certificate[] chain = new Certificate[2];
        chain[0] = keyCert;
        chain[1] = trusedCert;

        // import the key entry.
        ks.setKeyEntry("key-entry-" + i, priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
    kmf.init(ks, passphrase);

    ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    ks = null;

    return ctx;
}
 
Example 17
Source File: RollingUpdateST.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Description("Test for checking that overriding of bootstrap server, triggers the rolling update and verifying that" +
        " new bootstrap DNS is appended inside certificate in subject alternative names property.")
@Test
void testTriggerRollingUpdateAfterOverrideBootstrap() throws CertificateException {
    String bootstrapDns = "kafka-test.XXXX.azure.XXXX.net";

    KafkaResource.kafkaPersistent(CLUSTER_NAME, 3, 3).done();

    Map<String, String> kafkaPods = StatefulSetUtils.ssSnapshot(KafkaResources.kafkaStatefulSetName(CLUSTER_NAME));

    KafkaResource.replaceKafkaResource(CLUSTER_NAME, kafka -> {

        LOGGER.info("Adding new bootstrap dns: {} to external listeners", bootstrapDns);
        kafka.getSpec().getKafka().getListeners().setExternal(
            new KafkaListenerExternalNodePortBuilder()
                .withNewOverrides()
                    .withNewBootstrap()
                        .withAddress(bootstrapDns)
                    .endBootstrap()
                .endOverrides()
                .build());
    });

    StatefulSetUtils.waitTillSsHasRolled(KafkaResources.kafkaStatefulSetName(CLUSTER_NAME), 3, kafkaPods);
    KafkaUtils.waitForKafkaReady(CLUSTER_NAME);

    String bootstrapAddressDns = ((KafkaListenerExternalNodePort) Crds.kafkaOperation(kubeClient().getClient())
            .inNamespace(kubeClient().getNamespace()).withName(CLUSTER_NAME).get().getSpec().getKafka()
            .getListeners().getExternal()).getOverrides().getBootstrap().getAddress();

    Map<String, String> secretData = kubeClient().getSecret(KafkaResources.brokersServiceName(CLUSTER_NAME)).getData();

    for (Map.Entry<String, String> item : secretData.entrySet()) {
        if (item.getKey().endsWith(".crt")) {
            LOGGER.info("Encoding {} cert", item.getKey());
            ByteArrayInputStream publicCert = new ByteArrayInputStream(Base64.getDecoder().decode(item.getValue().getBytes()));
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            Certificate certificate = certificateFactory.generateCertificate(publicCert);

            LOGGER.info("Verifying that new DNS is in certificate subject alternative names");
            assertThat(certificate.toString(), containsString(bootstrapAddressDns));
        }
    }

    LOGGER.info("Verifying that new DNS is inside kafka CR");
    assertThat(bootstrapAddressDns, is(bootstrapDns));
}
 
Example 18
Source File: MerlinWithCRLDistributionPointsExtensionTest.java    From eet-client with MIT License 4 votes vote down vote up
private X509Certificate getEETCertificate(final String path) throws CertificateException {
    final InputStream is = getClass().getResourceAsStream(path);
    final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    return (X509Certificate) certificateFactory.generateCertificate(is);
}
 
Example 19
Source File: ServerHelloSSLv2.java    From DeepViolet with Apache License 2.0 4 votes vote down vote up
ServerHelloSSLv2(InputStream in)
	throws IOException
{
	// Record length
	byte[] buf = new byte[2];
	CipherSuiteUtil.readFully(in, buf);
	int len = CipherSuiteUtil.dec16be(buf, 0);
	if ((len & 0x8000) == 0) {
		throw new IOException("not a SSLv2 record");
	}
	len &= 0x7FFF;
	if (len < 11) {
		throw new IOException(
			"not a SSLv2 server hello");
	}
	buf = new byte[11];
	CipherSuiteUtil.readFully(in, buf);
	if (buf[0] != 0x04) {
		throw new IOException(
			"not a SSLv2 server hello");
	}
	int certLen = CipherSuiteUtil.dec16be(buf, 5);
	int csLen = CipherSuiteUtil.dec16be(buf, 7);
	int connIdLen = CipherSuiteUtil.dec16be(buf, 9);
	if (len != 11 + certLen + csLen + connIdLen) {
		throw new IOException(
			"not a SSLv2 server hello");
	}
	if (csLen == 0 || csLen % 3 != 0) {
		throw new IOException(
			"not a SSLv2 server hello");
	}
	byte[] cert = new byte[certLen];
	CipherSuiteUtil.readFully(in, cert);
	byte[] cs = new byte[csLen];
	CipherSuiteUtil.readFully(in, cs);
	byte[] connId = new byte[connIdLen];
	CipherSuiteUtil.readFully(in, connId);
	cipherSuites = new int[csLen / 3];
	for (int i = 0, j = 0; i < csLen; i += 3, j ++) {
		cipherSuites[j] = CipherSuiteUtil.dec24be(cs, i);
	}
	try {
		CertificateFactory cf =
			CertificateFactory.getInstance("X.509");
		X509Certificate xc =
			(X509Certificate)cf.generateCertificate(
				new ByteArrayInputStream(cert));
		serverCertName =
			xc.getSubjectX500Principal().toString();
		serverCertHash = CipherSuiteUtil.doSHA1(cert);
	} catch (CertificateException e) {
		// ignored
	}
}
 
Example 20
Source File: ValidatorCRLTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
private X509Certificate readCertificate(String path) throws CertificateException {
    InputStream inputStream = ValidatorCRLTest.class.getResourceAsStream(PATH_TO_RESOURCES + path);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    return (X509Certificate)cf.generateCertificate(inputStream);
}