java.security.cert.CertificateFactory#generateCertificate()源码实例Demo

下面列出了java.security.cert.CertificateFactory#generateCertificate() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: TencentKona-8   文件: NoExtensions.java
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);
}
 
源代码2 项目: bluemix-parking-meter   文件: HttpResponseCache.java
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());
  }
}
 
源代码3 项目: tessera   文件: SSLKeyStoreLoader.java
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;
}
 
源代码4 项目: grpc-java   文件: TestUtils.java
/**
 * 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();
}
 
源代码5 项目: athenz   文件: CertificateAuthorityTest.java
@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"));
    }
}
 
源代码6 项目: TrustKit-Android   文件: CertificateUtils.java
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");
    }
}
 
源代码7 项目: athenz   文件: AthenzUtilsTest.java
@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));
    }
}
 
源代码8 项目: syndesis   文件: CertificateUtil.java
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;
}
 
源代码9 项目: IDES-Data-Preparation-Java   文件: UtilShared.java
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;
	}
}
 
源代码10 项目: protools   文件: ToolCertificate2.java
/**
 * 获得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;
}
 
源代码11 项目: keywhiz   文件: ClientAuthenticatorTest.java
@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);
}
 
源代码12 项目: swellrt   文件: Certificates.java
/**
 * 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);
}
 
源代码13 项目: nifi   文件: CertificateUtils.java
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;
    }
}
 
源代码14 项目: ecosys   文件: Util.java
/**
 * 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);
  }
}
 
源代码15 项目: openjdk-jdk9   文件: SunX509ExtendedTM.java
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;
}
 
源代码16 项目: dragonwell8_jdk   文件: ECCurvesconstraints.java
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;
}
 
源代码17 项目: strimzi-kafka-operator   文件: RollingUpdateST.java
@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));
}
 
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);
}
 
源代码19 项目: DeepViolet   文件: ServerHelloSSLv2.java
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
	}
}
 
源代码20 项目: cxf   文件: ValidatorCRLTest.java
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);
}