java.security.cert.CertificateFactory Java Examples

The following examples show how to use java.security.cert.CertificateFactory. 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 openjdk-8-source with GNU General Public License v2.0 8 votes vote down vote up
private static X509Certificate getUserCertificate1() throws Exception {
    // this certificate includes an extension
    String sCert =
        "-----BEGIN CERTIFICATE-----\n"
      + "MIIBfzCCASmgAwIBAgIQWFSKzCWO2ptOAc2F3MKZSzANBgkqhkiG9w0BAQQFADAa\n"
      + "MRgwFgYDVQQDEw9Sb290Q2VydGlmaWNhdGUwHhcNMDExMDE5MTMwNzQxWhcNMzkx\n"
      + "MjMxMjM1OTU5WjAaMRgwFgYDVQQDEw9Vc2VyQ2VydGlmaWNhdGUwXDANBgkqhkiG\n"
      + "9w0BAQEFAANLADBIAkEA24gypa2YFGZHKznEWWbqIWNVXCM35W7RwJwhGpNsuBCj\n"
      + "NT6KEo66F+OOMgZmb0KrEZHBJASJ3n4Cqbt4aHm/2wIDAQABo0swSTBHBgNVHQEE\n"
      + "QDA+gBBch+eYzOPgVRbMq5vGpVWooRgwFjEUMBIGA1UEAxMLUm9vdCBBZ2VuY3mC\n"
      + "EMlg/HS1KKqSRcg8a30Za7EwDQYJKoZIhvcNAQEEBQADQQCYBIHBqQQJePi5Hzfo\n"
      + "CxeUaYlXmvbxVNkxM65Pplsj3h4ntfZaynmlhahH3YsnnA8wk6xPt04LjSId12RB\n"
      + "PeuO\n"
      + "-----END CERTIFICATE-----";
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bytes = new ByteArrayInputStream(sCert.getBytes());
    return (X509Certificate)certFactory.generateCertificate(bytes);
}
 
Example #2
Source File: SignatureFileVerifier.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create the named SignatureFileVerifier.
 *
 * @param name the name of the signature block file (.DSA/.RSA/.EC)
 *
 * @param rawBytes the raw bytes of the signature block file
 */
public SignatureFileVerifier(ArrayList<CodeSigner[]> signerCache,
                             ManifestDigester md,
                             String name,
                             byte[] rawBytes)
    throws IOException, CertificateException
{
    // new PKCS7() calls CertificateFactory.getInstance()
    // need to use local providers here, see Providers class
    Object obj = null;
    try {
        obj = Providers.startJarVerification();
        block = new PKCS7(rawBytes);
        sfBytes = block.getContentInfo().getData();
        certificateFactory = CertificateFactory.getInstance("X509");
    } finally {
        Providers.stopJarVerification(obj);
    }
    this.name = name.substring(0, name.lastIndexOf('.'))
                                               .toUpperCase(Locale.ENGLISH);
    this.md = md;
    this.signerCache = signerCache;
}
 
Example #3
Source File: Auth.java    From jenkins-plugin with Apache License 2.0 6 votes vote down vote up
private static Collection<X509Certificate> createCert(File caCertFile,
        String certString, TaskListener listener, String apiURL)
        throws Exception {
    if (listener != null && certString != null) {
        listener.getLogger().println(
                "Auth - using user inputted cert string");
    }
    InputStream pemInputStream = null;
    try {
        pemInputStream = getInputStreamFromDataOrFile(certString,
                caCertFile);
        CertificateFactory certFactory = CertificateFactory
                .getInstance("X509");
        return (Collection<X509Certificate>) certFactory
                .generateCertificates(pemInputStream);
    } finally {
        if (pemInputStream != null) {
            pemInputStream.close();
        }
    }
}
 
Example #4
Source File: ExportControlled.java    From r-course with MIT License 6 votes vote down vote up
public X509TrustManagerWrapper(X509TrustManager tm, boolean verifyServerCertificate) throws CertificateException {
    this.origTm = tm;
    this.verifyServerCert = verifyServerCertificate;

    if (verifyServerCertificate) {
        try {
            Set<TrustAnchor> anch = new HashSet<TrustAnchor>();
            for (X509Certificate cert : tm.getAcceptedIssuers()) {
                anch.add(new TrustAnchor(cert, null));
            }
            this.validatorParams = new PKIXParameters(anch);
            this.validatorParams.setRevocationEnabled(false);
            this.validator = CertPathValidator.getInstance("PKIX");
            this.certFactory = CertificateFactory.getInstance("X.509");
        } catch (Exception e) {
            throw new CertificateException(e);
        }
    }
}
 
Example #5
Source File: HttpResponseCache.java    From CordovaYoutubeVideoPlayer 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: ValidateTargetConstraints.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public static void createPath(String[] certs) throws Exception {
    TrustAnchor anchor = new TrustAnchor(getCertFromFile(certs[0]), null);
    List list = new ArrayList();
    for (int i = 1; i < certs.length; i++) {
        list.add(0, getCertFromFile(certs[i]));
    }
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    path = cf.generateCertPath(list);

    Set anchors = Collections.singleton(anchor);
    params = new PKIXParameters(anchors);
    params.setRevocationEnabled(false);
    X509CertSelector sel = new X509CertSelector();
    sel.setSerialNumber(new BigInteger("1427"));
    params.setTargetCertConstraints(sel);
}
 
Example #7
Source File: ValidateNC.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void createPath(String[] certs) throws Exception {

        X509Certificate anchorCert = getCertFromFile(certs[0]);
        byte [] nameConstraints = anchorCert.getExtensionValue("2.5.29.30");
        if (nameConstraints != null) {
            DerInputStream in = new DerInputStream(nameConstraints);
            nameConstraints = in.getOctetString();
        }
        TrustAnchor anchor = new TrustAnchor(anchorCert, nameConstraints);
        List list = new ArrayList();
        for (int i = 1; i < certs.length; i++) {
            list.add(0, getCertFromFile(certs[i]));
        }
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        path = cf.generateCertPath(list);

        anchors = Collections.singleton(anchor);
        params = new PKIXParameters(anchors);
        params.setRevocationEnabled(false);
    }
 
Example #8
Source File: SignatureFileVerifier.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create the named SignatureFileVerifier.
 *
 * @param name the name of the signature block file (.DSA/.RSA/.EC)
 *
 * @param rawBytes the raw bytes of the signature block file
 */
public SignatureFileVerifier(ArrayList<CodeSigner[]> signerCache,
                             ManifestDigester md,
                             String name,
                             byte rawBytes[])
    throws IOException, CertificateException
{
    // new PKCS7() calls CertificateFactory.getInstance()
    // need to use local providers here, see Providers class
    Object obj = null;
    try {
        obj = Providers.startJarVerification();
        block = new PKCS7(rawBytes);
        sfBytes = block.getContentInfo().getData();
        certificateFactory = CertificateFactory.getInstance("X509");
    } finally {
        Providers.stopJarVerification(obj);
    }
    this.name = name.substring(0, name.lastIndexOf("."))
                                               .toUpperCase(Locale.ENGLISH);
    this.md = md;
    this.signerCache = signerCache;
}
 
Example #9
Source File: HttpResponseCache.java    From crosswalk-cordova-android with Apache License 2.0 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 #10
Source File: X509CRLSelector2Test.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * setCertificateChecking(X509Certificate) method testing.
 */
public void testSetCertificateCheckingLjava_X509Certificate()
        throws CertificateException {
    X509CRLSelector selector = new X509CRLSelector();

    CertificateFactory certFact = CertificateFactory.getInstance("X509");
    X509Certificate cert = (X509Certificate) certFact
            .generateCertificate(new ByteArrayInputStream(TestUtils
                    .getX509Certificate_v3()));

    TestCRL crl = new TestCRL();
    selector.setCertificateChecking(cert);
    assertTrue("The CRL should match the selection criteria.", selector
            .match(crl));
    assertEquals(cert, selector.getCertificateChecking());

    selector.setCertificateChecking(null);
    assertTrue("The CRL should match the selection criteria.", selector
            .match(crl));
    assertNull(selector.getCertificateChecking());
}
 
Example #11
Source File: X509SubjectPrincipalResolverTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new test instance with the given parameters.
 *
 * @param certPath
 * @param descriptor
 * @param expectedResult
 */
public X509SubjectPrincipalResolverTests(
        final String certPath,
        final String descriptor,
        final String expectedResult) {

    this.resolver = new X509SubjectPrincipalResolver();
    this.resolver.setDescriptor(descriptor);
    try {
        this.certificate = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(
                new FileInputStream(certPath));
    } catch (final Exception e) {
        Assert.fail(String.format("Error parsing certificate %s: %s", certPath, e.getMessage()));
    }
    this.expected = expectedResult;
}
 
Example #12
Source File: SigningCertificate.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public SigningCertificate(String certificateChain, KeyStore trustStore)
    throws CertificateException, CertPathValidatorException
{
  try {
    CertificateFactory          certificateFactory     = CertificateFactory.getInstance("X.509");
    Collection<X509Certificate> certificatesCollection = (Collection<X509Certificate>) certificateFactory.generateCertificates(new ByteArrayInputStream(certificateChain.getBytes()));
    List<X509Certificate>       certificates           = new LinkedList<>(certificatesCollection);
    PKIXParameters              pkixParameters         = new PKIXParameters(trustStore);
    CertPathValidator           validator              = CertPathValidator.getInstance("PKIX");

    if (certificates.isEmpty()) {
      throw new CertificateException("No certificates available! Badly-formatted cert chain?");
    }

    this.path = certificateFactory.generateCertPath(certificates);

    pkixParameters.setRevocationEnabled(false);
    validator.validate(path, pkixParameters);
    verifyDistinguishedName(path);
  } catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}
 
Example #13
Source File: NoExtensions.java    From jdk8u-jdk 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 #14
Source File: ALiyunIotX509TrustManager.java    From rpi with Apache License 2.0 6 votes vote down vote up
public ALiyunIotX509TrustManager() throws Exception{
     //CA根证书,可以从官网下载
     InputStream in = SimpleClient4IOT.class.getResourceAsStream("/root.crt");
     CertificateFactory cf = CertificateFactory.getInstance("X.509");
     Certificate ca = null;
     try {
         ca = cf.generateCertificate(in);
     } catch (CertificateException e) {
        throw e;
     } finally {
         in.close();
     }
     String keyStoreType = KeyStore.getDefaultType();
     KeyStore keyStore = KeyStore.getInstance(keyStoreType);
     keyStore.load(null, null);
     keyStore.setCertificateEntry("ca", ca);
     String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
     TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
     tmf.init(keyStore);
     
     rootTrusm = (X509TrustManager) tmf.getTrustManagers()[0];

}
 
Example #15
Source File: MQTTSimulator.java    From device-simulator with Apache License 2.0 6 votes vote down vote up
@SneakyThrows
public SslContext getSSLContext() {

    if (ssl && sslContext == null) {
        Objects.requireNonNull(p12Path, "p12Path不能为空");
        Objects.requireNonNull(cerPath, "cerPath不能为空");
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(new FileInputStream(p12Path), p12Password.toCharArray());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        CertificateFactory cAf = CertificateFactory.getInstance("X.509");
        FileInputStream caIn = new FileInputStream(cerPath);
        X509Certificate ca = (X509Certificate) cAf.generateCertificate(caIn);
        KeyStore caKs = KeyStore.getInstance("JKS");
        caKs.load(null, null);
        caKs.setCertificateEntry("ca-certificate", ca);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(caKs);
        keyManagerFactory.init(keyStore, p12Password.toCharArray());
        sslContext = SslContextBuilder.forServer(keyManagerFactory)
                .trustManager(tmf)
                .build();
    }
    return sslContext;
}
 
Example #16
Source File: NoExtensions.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private static X509Certificate getTrustedCertificate() throws Exception {
    String sCert =
        "-----BEGIN CERTIFICATE-----\n"
      + "MIIBezCCASWgAwIBAgIQyWD8dLUoqpJFyDxrfRlrsTANBgkqhkiG9w0BAQQFADAW\n"
      + "MRQwEgYDVQQDEwtSb290IEFnZW5jeTAeFw0wMTEwMTkxMjU5MjZaFw0zOTEyMzEy\n"
      + "MzU5NTlaMBoxGDAWBgNVBAMTD1Jvb3RDZXJ0aWZpY2F0ZTBcMA0GCSqGSIb3DQEB\n"
      + "AQUAA0sAMEgCQQC+NFKszPjatUZKWmyWaFjir1wB93FX2u5SL+GMjgUsMs1JcTKQ\n"
      + "Kh0cnnQKknNkV4cTW4NPn31YCoB1+0KA3mknAgMBAAGjSzBJMEcGA1UdAQRAMD6A\n"
      + "EBLkCS0GHR1PAI1hIdwWZGOhGDAWMRQwEgYDVQQDEwtSb290IEFnZW5jeYIQBjds\n"
      + "AKoAZIoRz7jUqlw19DANBgkqhkiG9w0BAQQFAANBACJxAfP57yqaT9N+nRgAOugM\n"
      + "JG0aN3/peCIvL3p29epRL2xoWFvxpUUlsH2I39OZ6b8+twWCebhkv1I62segXAk=\n"
      + "-----END CERTIFICATE-----";
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bytes = new ByteArrayInputStream(sCert.getBytes());
    return (X509Certificate)certFactory.generateCertificate(bytes);
}
 
Example #17
Source File: ValidateNC.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public static void createPath(String[] certs) throws Exception {

        X509Certificate anchorCert = getCertFromFile(certs[0]);
        byte [] nameConstraints = anchorCert.getExtensionValue("2.5.29.30");
        if (nameConstraints != null) {
            DerInputStream in = new DerInputStream(nameConstraints);
            nameConstraints = in.getOctetString();
        }
        TrustAnchor anchor = new TrustAnchor(anchorCert, nameConstraints);
        List list = new ArrayList();
        for (int i = 1; i < certs.length; i++) {
            list.add(0, getCertFromFile(certs[i]));
        }
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        path = cf.generateCertPath(list);

        anchors = Collections.singleton(anchor);
        params = new PKIXParameters(anchors);
        params.setRevocationEnabled(false);
    }
 
Example #18
Source File: X509CertUtil.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private static X509Certificate[] loadCertificatesPkiPath(InputStream is) throws CryptoException {
	try {
		CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce());
		CertPath certPath = cf.generateCertPath(is, PKI_PATH_ENCODING);

		List<? extends Certificate> certs = certPath.getCertificates();

		ArrayList<X509Certificate> loadedCerts = new ArrayList<>();

		for (Iterator<? extends Certificate> itr = certs.iterator(); itr.hasNext();) {
			X509Certificate cert = (X509Certificate) itr.next();

			if (cert != null) {
				loadedCerts.add(cert);
			}
		}

		return loadedCerts.toArray(new X509Certificate[loadedCerts.size()]);
	} catch (CertificateException | NoSuchProviderException e) {
		throw new CryptoException(res.getString("NoLoadPkiPath.exception.message"), e);
	} finally {
		IOUtils.closeQuietly(is);
	}
}
 
Example #19
Source File: ValidateTargetConstraints.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void createPath(String[] certs) throws Exception {
    TrustAnchor anchor = new TrustAnchor(getCertFromFile(certs[0]), null);
    List list = new ArrayList();
    for (int i = 1; i < certs.length; i++) {
        list.add(0, getCertFromFile(certs[i]));
    }
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    path = cf.generateCertPath(list);

    Set anchors = Collections.singleton(anchor);
    params = new PKIXParameters(anchors);
    params.setRevocationEnabled(false);
    X509CertSelector sel = new X509CertSelector();
    sel.setSerialNumber(new BigInteger("1427"));
    params.setTargetCertConstraints(sel);
}
 
Example #20
Source File: ValidateNC.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void createPath(String[] certs) throws Exception {

        X509Certificate anchorCert = getCertFromFile(certs[0]);
        byte [] nameConstraints = anchorCert.getExtensionValue("2.5.29.30");
        if (nameConstraints != null) {
            DerInputStream in = new DerInputStream(nameConstraints);
            nameConstraints = in.getOctetString();
        }
        TrustAnchor anchor = new TrustAnchor(anchorCert, nameConstraints);
        List list = new ArrayList();
        for (int i = 1; i < certs.length; i++) {
            list.add(0, getCertFromFile(certs[i]));
        }
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        path = cf.generateCertPath(list);

        anchors = Collections.singleton(anchor);
        params = new PKIXParameters(anchors);
        params.setRevocationEnabled(false);
    }
 
Example #21
Source File: GenerationTests.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
static void test_create_signature_x509_crt_crl() throws Exception {
    System.out.println("* Generating signature-x509-crt-crl.xml");
    List<Object> xds = new ArrayList<Object>();
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    xds.add(signingCert);
    FileInputStream fis = new FileInputStream(CRL);
    X509CRL crl = (X509CRL) cf.generateCRL(fis);
    fis.close();
    xds.add(crl);
    KeyInfo crt_crl = kifac.newKeyInfo(Collections.singletonList
        (kifac.newX509Data(xds)));

    test_create_signature_external(dsaSha1, crt_crl, signingKey,
        new X509KeySelector(ks), false);
    System.out.println();
}
 
Example #22
Source File: KeyStoreUtilTest.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testExceptionCRLException() {
  String crlfile = strFilePath + "/ssl/server.p12";
  boolean validAssert = true;
  try {
    new MockUp<CertificateFactory>() {
      @Mock
      public final CertificateFactory getInstance(String type) throws CertificateException, CRLException {
        throw new CRLException();
      }
    };
    KeyStoreUtil.createCRL(crlfile);
  } catch (Exception e) {
    validAssert = false;
    Assert.assertEquals("java.lang.IllegalArgumentException", e.getClass().getName());
  }
  Assert.assertFalse(validAssert);
}
 
Example #23
Source File: HttpLogClient.java    From certificate-transparency-java with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the response from "get-roots" GET method.
 *
 * @param response JSONObject with certificates to parse.
 * @return a list of root certificates.
 */
List<Certificate> parseRootCertsResponse(String response) {
  List<Certificate> certs = new ArrayList<>();

  JSONObject entries = (JSONObject) JSONValue.parse(response);
  JSONArray entriesArray = (JSONArray) entries.get("certificates");

  for (Object i : entriesArray) {
    // We happen to know that JSONArray contains strings.
    byte[] in = Base64.decodeBase64((String) i);
    try {
      certs.add(
          CertificateFactory.getInstance("X509")
              .generateCertificate(new ByteArrayInputStream(in)));
    } catch (CertificateException e) {
      throw new CertificateTransparencyException(
          "Malformed data from a CT log have been received: " + e.getLocalizedMessage(), e);
    }
  }
  return certs;
}
 
Example #24
Source File: ConfigHelper.java    From bitmask_android with GNU General Public License v3.0 6 votes vote down vote up
public static X509Certificate parseX509CertificateFromString(String certificateString) {
    java.security.cert.Certificate certificate = null;
    CertificateFactory cf;
    try {
        cf = CertificateFactory.getInstance("X.509");

        certificateString = certificateString.replaceFirst("-----BEGIN CERTIFICATE-----", "").replaceFirst("-----END CERTIFICATE-----", "").trim();
        byte[] cert_bytes = Base64.decode(certificateString);
        InputStream caInput = new ByteArrayInputStream(cert_bytes);
        try {
            certificate = cf.generateCertificate(caInput);
            System.out.println("ca=" + ((X509Certificate) certificate).getSubjectDN());
        } finally {
            caInput.close();
        }
    } catch (NullPointerException | CertificateException | IOException | IllegalArgumentException e) {
        return null;
    }
    return (X509Certificate) certificate;
}
 
Example #25
Source File: IdentityApplicationManagementUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Generate thumbprint of certificate
 *
 * @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);
    }
}
 
Example #26
Source File: VerifyNameConstraints.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void createPath(String[] certs) throws Exception {
    TrustAnchor anchor = new TrustAnchor(getCertFromFile(certs[0]), null);
    List list = new ArrayList();
    for (int i = 1; i < certs.length; i++) {
        list.add(0, getCertFromFile(certs[i]));
    }
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    path = cf.generateCertPath(list);

    Set anchors = Collections.singleton(anchor);
    params = new PKIXParameters(anchors);
    params.setRevocationEnabled(false);
}
 
Example #27
Source File: SignatureFileVerifier.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create the named SignatureFileVerifier.
 *
 * @param name the name of the signature block file (.DSA/.RSA/.EC)
 *
 * @param rawBytes the raw bytes of the signature block file
 */
public SignatureFileVerifier(ArrayList<CodeSigner[]> signerCache,
                             ManifestDigester md,
                             String name,
                             byte rawBytes[])
    throws IOException, CertificateException
{
    // new PKCS7() calls CertificateFactory.getInstance()
    // need to use local providers here, see Providers class
    Object obj = null;
    try {
        obj = Providers.startJarVerification();
        block = new PKCS7(rawBytes);
        sfBytes = block.getContentInfo().getData();
        certificateFactory = CertificateFactory.getInstance("X509");
    } finally {
        Providers.stopJarVerification(obj);
    }
    this.name = name.substring(0, name.lastIndexOf("."))
                                               .toUpperCase(Locale.ENGLISH);
    this.md = md;
    this.signerCache = signerCache;
}
 
Example #28
Source File: BadPem.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 {
    String ks = System.getProperty("test.src", ".")
            + "/../../ssl/etc/keystore";
    String pass = "passphrase";
    String alias = "dummy";

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(ks), pass.toCharArray());
    byte[] cert = keyStore.getCertificate(alias).getEncoded();

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    PrintStream pout = new PrintStream(bout);
    byte[] CRLF = new byte[] {'\r', '\n'};
    pout.println(X509Factory.BEGIN_CERT);
    for (int i=0; i<cert.length; i += 48) {
        int blockLen = (cert.length > i + 48) ? 48 : (cert.length - i);
        pout.println("!" + Base64.getEncoder()
                .encodeToString(Arrays.copyOfRange(cert, i, i + blockLen)));
    }
    pout.println(X509Factory.END_CERT);

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

    try {
        cf.generateCertificate(new ByteArrayInputStream(bout.toByteArray()));
        throw new Exception("Should fail");
    } catch (CertificateException e) {
        // Good
    }
}
 
Example #29
Source File: CryptoUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static Certificate decodeCertificate(String encodedCert) {
    try {
        byte[] decoded = Base64Utility.decode(encodedCert);
        return CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(decoded));
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}
 
Example #30
Source File: AndroidHttpProvider.java    From actor-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
public SSLContext sslContextForTrustedCertificates(InputStream in) {
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        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.
        char[] password = "password".toCharArray(); // Any password will work.
        KeyStore keyStore = newEmptyKeyStore(password);
        int index = 0;
        for (Certificate certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificate);
        }

        // Wrap it up in an SSL context.
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
                KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());
        return sslContext;
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}