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); }
public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("Usage: java BlacklistedCertsConverter SHA-256" + " < blacklisted.certs.pem > blacklisted.certs"); System.exit(1); } String mdAlg = args[0]; CertificateFactory cf = CertificateFactory.getInstance("X.509"); Collection<? extends Certificate> certs = cf.generateCertificates(System.in); System.out.println("Algorithm=" + mdAlg); for (Certificate cert: certs) { System.out.println( getCertificateFingerPrint(mdAlg, (X509Certificate)cert)); } }
private String getKeyFromConfigServer(RestTemplate keyUriRestTemplate) throws CertificateException { // Load available UAA servers discoveryClient.getServices(); HttpEntity<Void> request = new HttpEntity<Void>(new HttpHeaders()); String content = keyUriRestTemplate .exchange("http://config/api/token_key", HttpMethod.GET, request, String.class).getBody(); if (StringUtils.isBlank(content)) { throw new CertificateException("Received empty certificate from config."); } InputStream fin = new ByteArrayInputStream(content.getBytes()); CertificateFactory f = CertificateFactory.getInstance(Constants.CERTIFICATE); X509Certificate certificate = (X509Certificate)f.generateCertificate(fin); PublicKey pk = certificate.getPublicKey(); return String.format(Constants.PUBLIC_KEY, new String(Base64.encode(pk.getEncoded()))); }
private List<Certificate> readCertificateList(BufferedSource source) throws IOException { int length = readInt(source); if (length == -1) return Collections.emptyList(); // OkHttp v1.2 used -1 to indicate null. try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); List<Certificate> result = new ArrayList<>(length); for (int i = 0; i < length; i++) { String line = source.readUtf8LineStrict(); Buffer bytes = new Buffer(); bytes.write(ByteString.decodeBase64(line)); result.add(certificateFactory.generateCertificate(bytes.inputStream())); } return result; } catch (CertificateException e) { throw new IOException(e.getMessage()); } }
@Test public void testCreateCRLException() { String crlfile = strFilePath + "/ssl/server.p12"; boolean validAssert = true; try { new MockUp<CertificateFactory>() { @Mock public final CertificateFactory getInstance(String type) throws CertificateException { throw new CertificateException(); } }; KeyStoreUtil.createCRL(crlfile); } catch (Exception e) { validAssert = false; } Assert.assertFalse(validAssert); }
/** * Generate Collection of Certificate from Input Stream * * @param stream InputStream of Certificate data * @return Collection<X509Certificate> * @throws PayPalRESTException */ @SuppressWarnings("unchecked") public static Collection<X509Certificate> getCertificateFromStream(InputStream stream) throws PayPalRESTException { if (stream == null) { throw new PayPalRESTException("Certificate Not Found"); } Collection<X509Certificate> certs = null; try { // Create a Certificate Factory CertificateFactory cf = CertificateFactory.getInstance("X.509"); // Read the Trust Certs certs = (Collection<X509Certificate>) cf.generateCertificates(stream); } catch (CertificateException ex) { throw new PayPalRESTException(ex); } return certs; }
private X509Certificate loadCert(Session session, long oHandle) throws PKCS11Exception, CertificateException { CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_VALUE) }; token.p11.C_GetAttributeValue(session.id(), oHandle, attrs); byte[] bytes = attrs[0].getByteArray(); if (bytes == null) { throw new CertificateException ("unexpectedly retrieved null byte array"); } CertificateFactory cf = CertificateFactory.getInstance("X.509"); return (X509Certificate)cf.generateCertificate (new ByteArrayInputStream(bytes)); }
/** * Method getX509Certificate * * @return the x509 certificate * @throws XMLSecurityException */ public X509Certificate getX509Certificate() throws XMLSecurityException { try { byte certbytes[] = this.getCertificateBytes(); CertificateFactory certFact = CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); X509Certificate cert = (X509Certificate) certFact.generateCertificate( new ByteArrayInputStream(certbytes) ); if (cert != null) { return cert; } return null; } catch (CertificateException ex) { throw new XMLSecurityException("empty", ex); } }
static void test(String... files) throws Exception { try (FileOutputStream fout = new FileOutputStream(OUTFILE)) { String here = System.getProperty("test.src", ""); for (String file: files) { Files.copy(Paths.get(here, file), fout); } } try (FileInputStream fin = new FileInputStream(OUTFILE)) { System.out.println("Testing " + Arrays.toString(files) + "..."); if (CertificateFactory.getInstance("X509") .generateCertificates(fin) .size() != files.length) { throw new Exception("Not same number"); } } Files.delete(Paths.get(OUTFILE)); }
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); }
public PKCS12KeyStoreSpi( Provider provider, ASN1ObjectIdentifier keyAlgorithm, ASN1ObjectIdentifier certAlgorithm) { this.keyAlgorithm = keyAlgorithm; this.certAlgorithm = certAlgorithm; try { if (provider != null) { certFact = CertificateFactory.getInstance("X.509", provider); } else { certFact = CertificateFactory.getInstance("X.509"); } } catch (Exception e) { throw new IllegalArgumentException("can't create cert factory - " + e.toString()); } }
/** * Reads in a X509Certificate. * * @return the X509Certificate * @throws IOException if an I/O error occured */ public Object parseObject(PemObject obj) throws IOException { ByteArrayInputStream bIn = new ByteArrayInputStream(obj.getContent()); try { CertificateFactory certFact = CertificateFactory.getInstance("X.509", provider); return certFact.generateCertificate(bIn); } catch (Exception e) { throw new PEMException("problem parsing cert: " + e.toString(), e); } }
static void test_create_signature_x509_crt_crl() throws Exception { System.out.println("* Generating signature-x509-crt-crl.xml"); List<Object> xds = new ArrayList<>(); 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(); }
private String getKeyFromAuthorizationServer(RestTemplate keyUriRestTemplate) throws CertificateException { // Load available UAA servers discoveryClient.getServices(); HttpEntity<Void> request = new HttpEntity<Void>(new HttpHeaders()); String content = keyUriRestTemplate .exchange("http://config/api/token_key", HttpMethod.GET, request, String.class).getBody(); if (StringUtils.isBlank(content)) { throw new CertificateException("Received empty certificate from config."); } InputStream fin = new ByteArrayInputStream(content.getBytes()); CertificateFactory f = CertificateFactory.getInstance(Constants.CERTIFICATE); X509Certificate certificate = (X509Certificate)f.generateCertificate(fin); PublicKey pk = certificate.getPublicKey(); return String.format(Constants.PUBLIC_KEY, new String(Base64.encode(pk.getEncoded()))); }
private static X509TrustManager getTrustManager() 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 trusted cert try (ByteArrayInputStream is = new ByteArrayInputStream(trustedCertStr.getBytes())) { Certificate trustedCert = cf.generateCertificate(is); ks.setCertificateEntry("RSA Export Signer", trustedCert); } // create the trust manager TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm); tmf.init(ks); return (X509TrustManager)tmf.getTrustManagers()[0]; }
private static List<X509Certificate> readCertificateChain(File certificateChainFile) throws IOException, GeneralSecurityException { String contents = Files.toString(certificateChainFile, US_ASCII); Matcher matcher = CERT_PATTERN.matcher(contents); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); List<X509Certificate> certificates = new ArrayList<>(); int start = 0; while (matcher.find(start)) { byte[] buffer = base64Decode(matcher.group(1)); certificates.add((X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(buffer))); start = matcher.end(); } return certificates; }
@Before public void setup () throws Exception { this.builder = new SignatureRequestBuilder (); this.builderNoId = new SignatureRequestBuilder ( false ); this.kpg = KeyPairGenerator.getInstance ( "DSA" ); this.kpg.initialize ( 512 ); this.kp = this.kpg.generateKeyPair (); this.signer = new RequestSigner ( new RequestSigner.Configuration () ); this.cf = CertificateFactory.getInstance ( "X.509" ); final X509CA ca1 = new X509CA ( this.cf, CA_FILE_1, Collections.singleton ( CRL_FILE_1 ) ); final X509CA ca2 = new X509CA ( this.cf, CA_FILE_2, null ); ca1.load (); ca2.load (); this.validator1 = new RequestValidator ( new X509KeySelector ( ca1 ) ); this.validator2 = new RequestValidator ( new X509KeySelector ( ca2 ) ); }
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); }
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); } } }
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); }
/** * Load the collection of CRLs. * */ protected Collection<? extends CRL> getCRLs(String crlf) throws IOException, CRLException, CertificateException { Collection<? extends CRL> crls = null; InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = ConfigFileLoader.getInputStream(crlf); crls = cf.generateCRLs(is); } catch (IOException iex) { throw iex; } catch (CRLException crle) { throw crle; } catch (CertificateException ce) { throw ce; } finally { if (is != null) { try { is.close(); } catch (Exception ex) { // Ignore } } } return crls; }
/** * Is this APK signed or is it a Debug build? * * @return true if it is not signed */ public static boolean isDebuggable() { boolean debuggable = false; Context ctx = AirQuickUtils.getContext(); try { PackageInfo pinfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_SIGNATURES); Signature signatures[] = pinfo.signatures; CertificateFactory cf = CertificateFactory.getInstance("X.509"); for (int i = 0; i < signatures.length; i++) { ByteArrayInputStream stream = new ByteArrayInputStream(signatures[i].toByteArray()); X509Certificate cert = (X509Certificate) cf.generateCertificate(stream); debuggable = cert.getSubjectX500Principal().equals(DEBUG_DN); if (debuggable) break; } } catch (NameNotFoundException | CertificateException ignored) { } return debuggable; }
/** * Creates a URICertStore. * * @param parameters specifying the URI */ URICertStore(CertStoreParameters params) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException { super(params); if (!(params instanceof URICertStoreParameters)) { throw new InvalidAlgorithmParameterException ("params must be instanceof URICertStoreParameters"); } this.uri = ((URICertStoreParameters) params).uri; // if ldap URI, use an LDAPCertStore to fetch certs and CRLs if (uri.getScheme().toLowerCase(Locale.ENGLISH).equals("ldap")) { ldap = true; ldapHelper = CertStoreHelper.getInstance("LDAP"); ldapCertStore = ldapHelper.getCertStore(uri); ldapPath = uri.getPath(); // strip off leading '/' if (ldapPath.charAt(0) == '/') { ldapPath = ldapPath.substring(1); } } try { factory = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { throw new RuntimeException(); } }
private Certificate[] tryParsePKIPathChain(File chainFile) throws IOException, FileNotFoundException, CertificateException { Certificate[] internalCertificateChain = null; CertificateFactory cf = CertificateFactory.getInstance("X.509"); try (FileInputStream inputStream = new FileInputStream(chainFile)) { CertPath certPath = cf.generateCertPath(inputStream); List<? extends Certificate> certList = certPath.getCertificates(); internalCertificateChain = certList.toArray(new Certificate[]{}); } catch (CertificateException e){ LOG.info("Tried and failed to parse file as a PKI :" + chainFile.getName(), e); } return internalCertificateChain; }
/** * Test logic (environment has set up) */ private void runTest() throws FileNotFoundException, CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException { Certificate cert; CertificateFactory cf; try (FileInputStream fi = new FileInputStream(CERT_PATH)) { cf = CertificateFactory.getInstance("X.509"); cert = cf.generateCertificate(fi); KeyStore ks = KeyStore.getInstance( Utils.KeyStoreType.pkcs12.name()); ks.load(null, null); ks.setCertificateEntry(ALIAS, cert); Utils.saveKeyStore(ks, KEYSTORE_PATH, PASSWORD); ks = Utils.loadKeyStore(KEYSTORE_PATH, Utils.KeyStoreType.pkcs12, PASSWORD); final Certificate ksCert = ks.getCertificate(ALIAS); if (!ksCert.equals(cert)) { err.println("Orig cert: " + cert.toString()); err.println("Cert from keystore: " + ksCert.toString()); throw new RuntimeException("Certificates don't match"); } } }
/** * Reads in a X509Certificate. * * @return the X509Certificate * @throws IOException if an I/O error occured */ private X509Certificate readCertificate( String endMarker) throws IOException { ByteArrayInputStream bIn = new ByteArrayInputStream(readBytes(endMarker)); try { CertificateFactory certFact = CertificateFactory.getInstance("X.509", provider); return (X509Certificate)certFact.generateCertificate(bIn); } catch (Exception e) { throw new IOException("problem parsing cert: " + e.toString()); } }
/** * 根据公钥Cer文本串读取公钥 * * @param pubKeyText * @return */ public static PublicKey getPublicKeyByText(String pubKeyText) { try { CertificateFactory certificateFactory = CertificateFactory.getInstance(BaofooRsaConst.KEY_X509); BufferedReader br = new BufferedReader(new StringReader(pubKeyText)); String line = null; StringBuilder keyBuffer = new StringBuilder(); while ((line = br.readLine()) != null) { if (!line.startsWith("-")) { keyBuffer.append(line); } } Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(keyBuffer.toString()))); return certificate.getPublicKey(); } catch (Exception e) { // log.error("解析公钥内容失败:", e); } return null; }
public static void setUpSSL(Context context) { // set up keystore try (InputStream clientInput = context.getResources().openRawResource(R.raw.rdw_poc_mdl_client_ca); //InputStream serverInput = context.getResources().openRawResource(R.raw.rdw_poc_ca)) { InputStream serverInput = context.getResources().openRawResource(R.raw.rdw_poc_ssl)) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); //java.security.cert.Certificate clientCA = cf.generateCertificate(clientInput); // This part sends my cert to server // KeyStore clientStore = KeyStore.getInstance("PKCS12"); // clientStore.load(clientInput, "password".toCharArray()); //clientStore.setCertificateEntry("", clientCA); // KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // keyManagerFactory.init(clientStore, null); // this part trusts a remote certificate java.security.cert.Certificate serverCA = cf.generateCertificate(serverInput); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore serverStore = KeyStore.getInstance("PKCS12"); serverStore.load(null, null); serverStore.setCertificateEntry("", serverCA); tmf.init(serverStore); SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, tmf.getTrustManagers(), null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { Log.e("TLS", "Something went wrong", e); } }
@Test @Ignore public void testTrusted() throws Exception { final Keychain k = new Keychain(); InputStream inStream = new FileInputStream("src/test/resources/OXxlRDVcWqdPEvFm.cer"); CertificateFactory cf = CertificateFactory.getInstance("X.509"); final X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream); assertTrue(k.isTrusted("test.cyberduck.ch", Collections.singletonList(cert))); }
public static X509Certificate makeCertFromPEM(String pemCert) throws CertificateException { CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream is = new ByteArrayInputStream(pemCert.getBytes()); return ((X509Certificate)cf.generateCertificate(is)); }
/** * Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose * certificates have not been signed by these certificates will fail with a {@code * SSLHandshakeException}. * * <p>This can be used to replace the host platform's built-in trusted certificates with a custom * set. This is useful in development where certificate authority-trusted certificates aren't * available. Or in production, to avoid reliance on third-party certificate authorities. * * <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using * the host platform's built-in trust store. * * <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3> * * <p>Relying on your own trusted certificates limits your server team's ability to update their * TLS certificates. By installing a specific set of trusted certificates, you take on additional * operational complexity and limit your ability to migrate between certificate authorities. Do * not use custom trusted certificates in production without the blessing of your server's TLS * administrator. */ private X509TrustManager trustManagerForCertificates(InputStream in) throws GeneralSecurityException { 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); } // Use it to build an X509 trust manager. KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, password); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } return (X509TrustManager) trustManagers[0]; }
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); }
/** * getSigningCredential loads up an X509Credential from a file. * * @param resource the signing certificate file * @return an X509 credential */ private Credential getSigningCredential(final Resource resource) { try (InputStream inputStream = resource.getInputStream()) { final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); final X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(inputStream); final Credential publicCredential = new BasicX509Credential(certificate); logger.debug("getSigningCredential: key retrieved."); return publicCredential; } catch (final Exception ex) { logger.error(ex.getMessage(), ex); return null; } }
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]); }
protected java.security.cert.X509Certificate [] getX509Certificates(SSLSession session) throws IOException { Certificate [] certs=null; try { certs = session.getPeerCertificates(); } catch( Throwable t ) { log.debug("Error getting client certs",t); return null; } if( certs==null ) return null; java.security.cert.X509Certificate [] x509Certs = new java.security.cert.X509Certificate[certs.length]; for(int i=0; i < certs.length; i++) { if (certs[i] instanceof java.security.cert.X509Certificate ) { // always currently true with the JSSE 1.1.x x509Certs[i] = (java.security.cert.X509Certificate) certs[i]; } else { try { byte [] buffer = certs[i].getEncoded(); CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream stream = new ByteArrayInputStream(buffer); x509Certs[i] = (java.security.cert.X509Certificate) cf.generateCertificate(stream); } catch(Exception ex) { log.info("Error translating cert " + certs[i], ex); return null; } } if(log.isTraceEnabled()) log.trace("Cert #" + i + " = " + x509Certs[i]); } if(x509Certs.length < 1) return null; return x509Certs; }