Java Code Examples for java.security.cert.CertificateFactory

The following examples show how to use java.security.cert.CertificateFactory. These examples are extracted from open source projects. 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
/**
 * 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 2
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 3
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 4
Source Project: jdk8u-jdk   Source File: ValidateNC.java    License: 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 5
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 6
Source Project: jdk8u-jdk   Source File: NoExtensions.java    License: 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 7
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 8
/**
 * 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 Project: CordovaYoutubeVideoPlayer   Source File: HttpResponseCache.java    License: 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 10
Source Project: rpi   Source File: ALiyunIotX509TrustManager.java    License: 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 11
Source Project: device-simulator   Source File: MQTTSimulator.java    License: 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 12
Source Project: openjdk-8   Source File: NoExtensions.java    License: 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 13
Source Project: bitmask_android   Source File: ConfigHelper.java    License: 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 14
/**
 * 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 15
Source Project: r-course   Source File: ExportControlled.java    License: 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 16
Source Project: jenkins-plugin   Source File: Auth.java    License: 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 17
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 18
Source Project: jdk8u-jdk   Source File: ValidateNC.java    License: 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 19
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 20
Source Project: j2objc   Source File: X509CRLSelector2Test.java    License: 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 21
/**
 * 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 22
Source Project: openjdk-8-source   Source File: ValidateNC.java    License: 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 23
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 24
Source Project: servicecomb-java-chassis   Source File: KeyStoreUtilTest.java    License: 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 25
Source Project: jam-collaboration-sample   Source File: SignatureUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static X509Certificate makeCertificate(String certificateBase64) {
    if (certificateBase64 == null || certificateBase64.isEmpty()) {
        throw new IllegalArgumentException("Supplied 'certificateBase64' argument is null or empty.");
    }

    try {
        byte[] certRaw = Base64Util.decode(certificateBase64);           
        CertificateFactory certFactory = CertificateFactory.getInstance(PUBLIC_CERT_ALGORITHM);
        return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(certRaw));
    } catch (Exception e) {
        throw new RuntimeException("Unable to deserialize supplied X509 certificate.", e);
    }
}
 
Example 26
Source Project: fdroidclient   Source File: JKS.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static Certificate readCert(DataInputStream in)
        throws IOException, CertificateException, NoSuchAlgorithmException {
    String type = in.readUTF();
    int len = in.readInt();
    byte[] encoded = new byte[len];
    in.read(encoded);
    CertificateFactory factory = CertificateFactory.getInstance(type);
    return factory.generateCertificate(new ByteArrayInputStream(encoded));
}
 
Example 27
/**
 * Read a bunch of certs from files and create a CertPath from them.
 *
 * @param relPath relative path containing certs (must end in
 *    file.separator)
 * @param fileNames an array of <code>String</code>s that are file names
 * @throws Exception on error
 */
public static CertPath buildPath(String relPath, String [] fileNames)
    throws Exception {
    List<X509Certificate> list = new ArrayList<X509Certificate>();
    for (int i = 0; i < fileNames.length; i++) {
        list.add(0, getCertFromFile(relPath + fileNames[i]));
    }
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    return(cf.generateCertPath(list));
}
 
Example 28
Source Project: jdk8u_jdk   Source File: OrderAndDup.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        // Generate 20 serial numbers with dup and a special order
        int count = 20;
        BigInteger[] serials = new BigInteger[count];
        for (int i=0; i<count; i++) {
            serials[i] = BigInteger.valueOf(i*7%10);
        }

        // Generates a CRL
        X509CRLEntry[] badCerts = new X509CRLEntry[count];
        for (int i=0; i<count; i++) {
            badCerts[i] = new X509CRLEntryImpl(serials[i],
                    new Date(System.currentTimeMillis()+i*1000));
        }
        X500Name owner = new X500Name("CN=CA");
        X509CRLImpl crl = new X509CRLImpl(owner, new Date(), new Date(), badCerts);
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        crl.sign(kpg.genKeyPair().getPrivate(), "SHA1withRSA");
        byte[] data = crl.getEncodedInternal();

        // Check the encoding
        checkData(crl, data, serials);

        // Load a CRL from raw data
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509CRLImpl crl2 = (X509CRLImpl)cf.generateCRL(new ByteArrayInputStream(data));

        // Check the encoding again
        data = crl2.getEncodedInternal();
        checkData(crl2, data, serials);
    }
 
Example 29
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 30
@Test
void clientConnectionTlsKeyCertPairCreatedIfNotExist() {
  final Path privateKeyPath = config.clientConnectionTlsServerKey();
  final Path certificatePath = config.clientConnectionTlsServerCert();

  assertThat(privateKeyPath).doesNotExist();
  assertThat(certificatePath).doesNotExist();

  try {
    // start Orion
    orion = new Orion(vertx);
    orion.run(config, false);

    // key/certificate created after Orion start and are in valid readable format.
    assertThat(privateKeyPath).exists();
    assertThat(certificatePath).exists();

    assertThatCode(() -> new PKCS8EncodedKeySpec(readPemFile(privateKeyPath))).doesNotThrowAnyException();

    assertThatCode(
        () -> CertificateFactory.getInstance("X.509").generateCertificate(
            new ByteArrayInputStream(Files.readAllBytes(certificatePath)))).doesNotThrowAnyException();
  } finally {
    if (orion != null) {
      orion.stop();
    }

    vertx.close();
  }
}