Java Examples for java.security.cert.X509Certificate

The following java examples will help you to understand the usage of java.security.cert.X509Certificate. These source code samples are taken from different open source projects.

Example 1
Project: aws-toolkit-eclipse-master  File: CertificateUtils.java View source code
public static void disableCertValidation() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    }
}
Example 2
Project: cougar-master  File: X509CertificateUtilsTest.java View source code
@Test
public void javaToJavaxToJava() throws Exception {
    KeyStoreManagement ksm = KeyStoreManagement.getKeyStoreManagement("JKS", new FileSystemResource(KeyStoreManagementTest.getKeystorePath()), "password");
    KeyStore ks = ksm.getKeyStore();
    long start = System.nanoTime();
    java.security.cert.X509Certificate c1 = (java.security.cert.X509Certificate) ks.getCertificate("selfsigned");
    javax.security.cert.X509Certificate c2 = X509CertificateUtils.convert(c1);
    java.security.cert.X509Certificate c3 = X509CertificateUtils.convert(c2);
    long total = System.nanoTime() - start;
    System.out.println("Total time: " + total);
    assertEquals(c1, c3);
}
Example 3
Project: blend4j-master  File: SslHacking.java View source code
public static void disableCertificateCheck() {
    javax.net.ssl.TrustManager x509 = new javax.net.ssl.X509TrustManager() {

        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
            return;
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
            return;
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("SSL");
        ctx.init(null, new javax.net.ssl.TrustManager[] { x509 }, null);
    } catch (java.security.GeneralSecurityException ex) {
    }
    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {

        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
}
Example 4
Project: identity-sample-apps-master  File: SSLValidationDisabler.java View source code
public static void disableSSLValidation() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };
    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    } catch (GeneralSecurityException e) {
    }
}
Example 5
Project: jgalaxy-master  File: Ssl.java View source code
public static void disableCertificateCheck() {
    javax.net.ssl.TrustManager x509 = new javax.net.ssl.X509TrustManager() {

        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
            return;
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
            return;
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("SSL");
        ctx.init(null, new javax.net.ssl.TrustManager[] { x509 }, null);
    } catch (java.security.GeneralSecurityException ex) {
    }
    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {

        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
}
Example 6
Project: BitTorrentApp-master  File: TrustALLSSLFactory.java View source code
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
    /*
                                                         * returning null here
                                                         * can cause a NPE in
                                                         * some java versions!
                                                         */
    return new java.security.cert.X509Certificate[0];
}
Example 7
Project: frostwire-common-master  File: TrustALLSSLFactory.java View source code
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
    /*
                                                         * returning null here
                                                         * can cause a NPE in
                                                         * some java versions!
                                                         */
    return new java.security.cert.X509Certificate[0];
}
Example 8
Project: POCenter-master  File: UnsafeOkHttpUtils.java View source code
/**
     * don't verify certificate
     * @return
     */
public static OkHttpClient getClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory);
        builder.hostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        OkHttpClient okHttpClient = builder.build();
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 9
Project: extension-aws-master  File: NaiveTrustManager.java View source code
public static void disableHttps() {
    if (disabled) {
        return;
    }
    disabled = true;
    // Install the all-trusting trust manager
    try {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    }
}
Example 10
Project: cagrid2-master  File: DorianCertificateAuthoritySHA2Upgrader.java View source code
/**
	 * @param args
	 */
public static void main(String[] args) {
    try {
        BootstrapperSpringUtils utils = new BootstrapperSpringUtils();
        CertificateAuthorityProperties props = utils.getCertificateAuthorityProperties();
        CertificateAuthority ca = utils.getCertificateAuthority();
        X509Certificate cert = ca.getCACertificate();
        PrivateKey key = ca.getPrivateKey();
        KeyPair pair = new KeyPair(cert.getPublicKey(), key);
        X509Certificate cacert = CertUtil.generateCACertificate("BC", new X509Name(cert.getSubjectDN().getName()), cert.getNotBefore(), cert.getNotAfter(), pair, "SHA256WITHRSAENCRYPTION");
        System.out.println(cacert.getSubjectDN().getName());
        String certStr = CertUtil.writeCertificate(cacert);
        utils.getDatabase().update("update " + CredentialsManager.CREDENTIALS_TABLE + " set CERTIFICATE='" + certStr + "'");
    // ca.setCACredentials(cacert, key,
    // props.getCertificateAuthorityPassword());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 11
Project: find-sec-bugs-master  File: WeakTrustManager.java View source code
public static void main(String[] args) {
    X509TrustManager anonymousClass = new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    };
    anonymousClass.getAcceptedIssuers();
}
Example 12
Project: ninuxmobile-master  File: CustomX509TrustManager.java View source code
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws CertificateException {
// Here you can verify the servers certificate. (e.g. against one which is stored on mobile device)
// InputStream inStream = null;
// try {
// inStream = MeaApplication.loadCertAsInputStream();
// CertificateFactory cf = CertificateFactory.getInstance("X.509");
// X509Certificate ca = (X509Certificate)
// cf.generateCertificate(inStream);
// inStream.close();
//
// for (X509Certificate cert : certs) {
// // Verifing by public key
// cert.verify(ca.getPublicKey());
// }
// } catch (Exception e) {
// throw new IllegalArgumentException("Untrusted Certificate!");
// } finally {
// try {
// inStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
}
Example 13
Project: cloudbreak-master  File: PkiUtilTest.java View source code
@Test
public void generateCert() throws Exception {
    KeyPair identityKey = PkiUtil.generateKeypair();
    KeyPair signKey = PkiUtil.generateKeypair();
    X509Certificate cert = PkiUtil.cert(identityKey, "192.168.99.100", signKey);
    String pk = PkiUtil.convert(identityKey.getPrivate());
    String cer = PkiUtil.convert(cert);
    Assert.assertNotNull(pk);
    Assert.assertNotNull(cer);
}
Example 14
Project: LittleProxy-mitm-master  File: CertificateSniffingMitmManager.java View source code
public SSLEngine clientSslEngineFor(HttpRequest httpRequest, SSLSession serverSslSession) {
    try {
        X509Certificate upstreamCert = getCertificateFromSession(serverSslSession);
        // TODO store the upstream cert by commonName to review it later
        // A reasons to not use the common name and the alternative names
        // from upstream certificate from serverSslSession to create the
        // dynamic certificate:
        //
        // It's not necessary. The host name is accepted by the browser.
        //
        String commonName = getCommonName(upstreamCert);
        SubjectAlternativeNameHolder san = new SubjectAlternativeNameHolder();
        san.addAll(upstreamCert.getSubjectAlternativeNames());
        LOG.debug("Subject Alternative Names: {}", san);
        return sslEngineSource.createCertForHost(commonName, san);
    } catch (Exception e) {
        throw new FakeCertificateException("Creation dynamic certificate failed", e);
    }
}
Example 15
Project: molecule-master  File: Trust.java View source code
public static TrustManager allCertificates() {
    return new X509TrustManager() {

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    };
}
Example 16
Project: SmartReceiptsLibrary-master  File: BetaSmartReceiptsHostConfiguration.java View source code
/**
     * Only meant for beta testing, so we don't have to buy another cert
     *
     * @return an UNSAFE {@link OkHttpClient}
     */
private static OkHttpClient.Builder getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @SuppressLint("TrustAllX509TrustManager")
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @SuppressLint("TrustAllX509TrustManager")
            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        final OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory);
        builder.hostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(interceptor);
        return builder;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 17
Project: webofneeds-master  File: AliasFromCNGenerator.java View source code
@Override
public String generateAlias(final X509Certificate certificate) throws CertificateException {
    String alias = null;
    try {
        X500Name dnName = new X500Name(certificate.getSubjectDN().getName());
        alias = dnName.getCommonName();
    } catch (IOException e) {
        throw new CertificateException("SubjectDN problem - cannot generate alias", e);
    }
    if (alias == null || alias.isEmpty()) {
        throw new CertificateException("CN is null - cannot accept as alias");
    }
    return alias;
}
Example 18
Project: android-tutorials-glide-master  File: UnsafeOkHttpClient.java View source code
public static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 19
Project: cats-master  File: SSLUtil.java View source code
/**
     * to disable the certificate validation.
     * 
     */
public static void disableCertificateValidation() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 20
Project: Mineshafter-Launcher-master  File: GameStarter.java View source code
private static void bypassTls() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    SSLContext sc;
    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
}
Example 21
Project: mobilecloud-15-master  File: UnsafeHttpsClient.java View source code
public static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 22
Project: programming-cloud-services-for-android-master  File: UnsafeHttpsClient.java View source code
public static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 23
Project: rsimulator-master  File: SecurityHandler.java View source code
public void initialize() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {

            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
    } catch (Exception e) {
        log.error("Can not initialize.", e);
    }
}
Example 24
Project: bc-java-master  File: JcaCertStore.java View source code
private static Collection convertCerts(Collection collection) throws CertificateEncodingException {
    List list = new ArrayList(collection.size());
    for (Iterator it = collection.iterator(); it.hasNext(); ) {
        Object o = it.next();
        if (o instanceof X509Certificate) {
            X509Certificate cert = (X509Certificate) o;
            try {
                list.add(new X509CertificateHolder(cert.getEncoded()));
            } catch (IOException e) {
                throw new CertificateEncodingException("unable to read encoding: " + e.getMessage());
            }
        } else {
            list.add((X509CertificateHolder) o);
        }
    }
    return list;
}
Example 25
Project: SplunkLucidDb-master  File: TrustAllSSLSocketFactory.java View source code
/**
     * Creates an "accept-all" SSLSocketFactory - ssl sockets will accept ANY
     * certificate sent to them - thus effectively just securing the
     * communications. This could be set in a HttpsURLConnection using
     * HttpsURLConnection.setSSLSocketFactory(.....)
     * 
     * @return SSLSocketFactory
     * @author Ledion Bitincka (Oct 5, 2007)
     */
public static SSLSocketFactory createSSLSocketFactory() {
    SSLSocketFactory sslsocketfactory = null;
    SSLContext sc = null;
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        sslsocketfactory = sc.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sslsocketfactory;
}
Example 26
Project: Tomcat-master  File: JSSESupport.java View source code
@Override
public java.security.cert.X509Certificate[] getPeerCertificateChain() throws IOException {
    // Look up the current SSLSession
    if (session == null)
        return null;
    Certificate[] certs = null;
    try {
        certs = session.getPeerCertificates();
    } catch (Throwable t) {
        log.debug(sm.getString("jsseSupport.clientCertError"), 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(sm.getString("jseeSupport.certTranslationError", certs[i]), ex);
                return null;
            }
        }
        if (log.isTraceEnabled())
            log.trace("Cert #" + i + " = " + x509Certs[i]);
    }
    if (x509Certs.length < 1)
        return null;
    return x509Certs;
}
Example 27
Project: AQUArinthia-master  File: SimpleFeedParser.java View source code
private static void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }
    } };
    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 28
Project: BTC-e-client-for-JavaFX-master  File: SimpleRequest.java View source code
public static String makeRequest(String url) {
    //TODO fix is required
    //to handle handshake exception
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    }
    StringBuilder out = new StringBuilder();
    try {
        HttpsURLConnection urlConnection = (HttpsURLConnection) (new URL(url)).openConnection();
        urlConnection.setRequestMethod("GET");
        if (urlConnection.getResponseCode() == 200) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                out.append(line);
            }
            rd.close();
        }
        urlConnection.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return out.toString();
}
Example 29
Project: cryptoapplet-master  File: MitycXAdESSignatureFactory.java View source code
public SignatureResult formatSignature(SignatureOptions signatureOptions) throws Exception {
    byte[] data = OS.inputStreamToByteArray(signatureOptions.getDataToSign());
    X509Certificate certificate = signatureOptions.getCertificate();
    PrivateKey privateKey = signatureOptions.getPrivateKey();
    Configuracion configuracion = new Configuracion();
    configuracion.cargarConfiguracion();
    FirmaXML sxml = new FirmaXML(configuracion);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    sxml.signFile(certificate.getSerialNumber(), certificate.getIssuerDN().toString(), certificate, new ByteArrayInputStream(data), null, "Certificate1,<root>", privateKey, bos, false);
    SignatureResult signatureResult = new SignatureResult();
    signatureResult.setValid(true);
    signatureResult.setSignatureData(new ByteArrayInputStream(bos.toByteArray()));
    return signatureResult;
}
Example 30
Project: drftpd-master  File: SSLGetContext.java View source code
public static SSLContext getSSLContext() throws GeneralSecurityException, IOException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    if (ctx != null)
        // reuse previous SSLContext
        return ctx;
    ctx = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    KeyStore ks = KeyStore.getInstance("JKS");
    FileInputStream fis = null;
    try {
        fis = new FileInputStream("drftpd.key");
        ks.load(fis, "drftpd".toCharArray());
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
    kmf.init(ks, "drftpd".toCharArray());
    ctx.init(kmf.getKeyManagers(), trustAllCerts, null);
    String[] ciphers = ctx.createSSLEngine().getSupportedCipherSuites();
    logger.info("Supported ciphers are as follows:");
    for (int x = 0; x < ciphers.length; x++) {
        logger.info(ciphers[x]);
    }
    /*		for (String cipher : ciphers) {
			logger.info(cipher);
		}
*/
    return ctx;
}
Example 31
Project: drftpd3-extended-master  File: SSLGetContext.java View source code
public static SSLContext getSSLContext() throws GeneralSecurityException, IOException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    if (ctx != null)
        // reuse previous SSLContext
        return ctx;
    ctx = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    KeyStore ks = KeyStore.getInstance("JKS");
    FileInputStream fis = null;
    try {
        fis = new FileInputStream("drftpd.key");
        ks.load(fis, "drftpd".toCharArray());
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
    kmf.init(ks, "drftpd".toCharArray());
    ctx.init(kmf.getKeyManagers(), trustAllCerts, null);
    String[] ciphers = ctx.createSSLEngine().getSupportedCipherSuites();
    logger.info("Supported ciphers are as follows:");
    for (int x = 0; x < ciphers.length; x++) {
        logger.info(ciphers[x]);
    }
    /*		for (String cipher : ciphers) {
			logger.info(cipher);
		}
*/
    return ctx;
}
Example 32
Project: jdk7u-jdk-master  File: NullGetAcceptedIssuers.java View source code
public static void main(String[] args) throws Exception {
    SSLContext sslContext;
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        // API says empty array, but some custom TMs are
        // returning null.
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };
    sslContext = javax.net.ssl.SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, null);
}
Example 33
Project: jplag-master  File: TrustAllSSLSocketFactory.java View source code
public static synchronized SocketFactory getDefault() {
    if (sockFac == null) {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            sockFac = sc.getSocketFactory();
        } catch (Exception e) {
        }
        tassf = new TrustAllSSLSocketFactory();
    }
    return tassf;
}
Example 34
Project: muikku-master  File: ClientPool.java View source code
private Client buildClient() {
    // TODO: trust all only on development environment
    ClientBuilder clientBuilder = ClientBuilder.newBuilder();
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (NoSuchAlgorithmExceptionKeyManagementException |  e) {
        logger.log(Level.SEVERE, "Failed to initialize trust all certificate manager", e);
    }
    HostnameVerifier fakeHostnameVerifier = new HostnameVerifier() {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    ClientBuilder builder = clientBuilder.sslContext(sslContext).hostnameVerifier(fakeHostnameVerifier).register(new JacksonConfigurator()).register(new BrowserCacheFeature());
    return builder.build();
}
Example 35
Project: nz.co.kakariki.WNMSExtract-master  File: SSLReaderUtilities.java View source code
public static void bypassSSLAuthentication() {
    System.err.println("SSL bypass using fake X509 Trust Manager requested");
    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new X509TrustManager[] { new X509TrustManager() {

            @SuppressWarnings("unused")
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            @SuppressWarnings("unused")
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {
            // TODO Auto-generated method stub
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {
            // TODO Auto-generated method stub
            }
        } }, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    } catch (Exception e) {
    }
}
Example 36
Project: OpenConext-api-master  File: OAuthRequestIgnoreCertificate.java View source code
/*
   * Incredible dirty hack to ensire we have a Connection that does not check
   * certificates. The extensibility of OAuthRequest is bad and therefore the
   * reflection 'trick'
   */
private void createUnsafeConnection() throws Exception {
    System.setProperty("http.keepAlive", "true");
    String completeUrl = getCompleteUrl();
    Field connField = getClass().getSuperclass().getSuperclass().getDeclaredField("connection");
    connField.setAccessible(true);
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    URLConnection openConnection = new URL(completeUrl).openConnection();
    connField.set(this, openConnection);
}
Example 37
Project: openjdk-master  File: NullGetAcceptedIssuers.java View source code
public static void main(String[] args) throws Exception {
    SSLContext sslContext;
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        // API says empty array, but some custom TMs are
        // returning null.
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };
    sslContext = javax.net.ssl.SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, null);
}
Example 38
Project: openjdk8-jdk-master  File: NullGetAcceptedIssuers.java View source code
public static void main(String[] args) throws Exception {
    SSLContext sslContext;
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        // API says empty array, but some custom TMs are
        // returning null.
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };
    sslContext = javax.net.ssl.SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, null);
}
Example 39
Project: performance-test-harness-for-geoevent-master  File: JsonEventProducer.java View source code
private void trustAll() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (GeneralSecurityException e) {
        System.out.println("Oops");
    }
}
Example 40
Project: puppetdb-javaclient-master  File: InsecureSSLSocketFactoryProvider.java View source code
@Override
public SSLSocketFactory get() {
    try {
        return new SSLSocketFactory(new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new ProvisionException("Unable to create SSLSocketFactory", e);
    }
}
Example 41
Project: webui-framework-master  File: SSLCertificateTruster.java View source code
/**
	 * This code was taken from an article entitled "Disabling Certificate Validation in an HTTPS Connection"
	 * http://www.exampledepot.com/egs/javax.net.ssl/TrustAll.html
	 */
public static void trustAllCerts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 42
Project: android-signage-client-master  File: TrustManager.java View source code
/**
     * Create a trust manager that does not validate certificate chains
     * @return 
     */
public static HostnameVerifier overrideCertificateChainValidation() {
    try {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[] { new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {

            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        // return the all-trusting host verifier
        return allHostsValid;
    } catch (KeyManagementException e) {
        Log.e(TAG, e.toString());
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, e.toString());
    }
    return null;
}
Example 43
Project: jira-rest-client-master  File: HttpConnectionUtil.java View source code
public static void disableSslVerification() {
    try {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {

            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
}
Example 44
Project: kraken-master  File: Util.java View source code
//
// Create a certificate from a PEM-encoded string.
//
public static java.security.cert.X509Certificate createCertificate(String certPEM) throws java.security.cert.CertificateException {
    final String header = "-----BEGIN CERTIFICATE-----";
    final String footer = "-----END CERTIFICATE-----";
    //
    // The generateCertificate method requires that its input begin
    // with the PEM header.
    //
    int pos = certPEM.indexOf(header);
    if (pos == -1) {
        certPEM = header + "\n" + certPEM;
    } else if (pos > 0) {
        certPEM = certPEM.substring(pos);
    }
    //
    if (certPEM.indexOf(footer) == -1) {
        certPEM = certPEM + footer;
    }
    byte[] bytes = null;
    try {
        bytes = certPEM.getBytes("UTF8");
    } catch (java.io.UnsupportedEncodingException ex) {
        assert (false);
        return null;
    }
    java.io.ByteArrayInputStream in = new java.io.ByteArrayInputStream(bytes);
    java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509");
    return (java.security.cert.X509Certificate) cf.generateCertificate(in);
}
Example 45
Project: ManalithBot-master  File: UrlUtils.java View source code
/**
	 * SSL 요청시 호스트를 따지지 않고 접�하�� 설정한다.
	 * https://github.com/mmx900/ManalithBot/issues/100 참고. TODO optional
	 * 
	 * @throws Exception
	 */
public static void setTrustAllHosts() throws Exception {
    // ��서를 검�하지 않는다.
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };
    SSLContext context = SSLContext.getInstance("SSL");
    context.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    // 호스트명� 검�하지 않는다.
    HttpsURLConnection.setDefaultHostnameVerifier(( hostname,  session) -> true);
}
Example 46
Project: OpenETSMobile2-master  File: AppletsApiCalendarRequest.java View source code
@Override
public EventList loadDataFromNetwork() throws Exception {
    String url = context.getString(R.string.applets_api_calendar, "ets", startDate, endDate);
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HostnameVerifier allHostsValid = new HostnameVerifier() {

        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    return getRestTemplate().getForObject(url, EventList.class);
}
Example 47
Project: ORCID-Source-master  File: DevJerseyClientConfig.java View source code
private SSLContext createSslContext() {
    try {
        // DANGER!!! Accepts all certs!
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        SSLContext ssl = SSLContext.getInstance("TLS");
        ssl.init(null, trustAllCerts, new SecureRandom());
        return ssl;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (KeyManagementException e) {
        throw new RuntimeException(e);
    }
}
Example 48
Project: s1tbx-master  File: SSLUtil.java View source code
public void disableSSLCertificateCheck() {
    hostnameVerifier = javax.net.ssl.HttpsURLConnection.getDefaultHostnameVerifier();
    javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {

        public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
            if (hostname.equals("qc.sentinel1.eo.esa.int")) {
                return true;
            }
            return false;
        }
    });
    final TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };
    try {
        final SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustManager, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (NoSuchAlgorithmExceptionKeyManagementException |  e) {
        SystemUtils.LOG.warning("disableSSLCertificateCheck failed: " + e);
    }
}
Example 49
Project: web-crawler-analysis-master  File: AllowAllTrustStrategy.java View source code
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    // also allow if certificate is not trusted.
    return true;
// else the connection will be aborted and we get no HTTP-Headers and no Certificate for this Website
// if we return false, the certificate gets also checked by the default
// environment
// throw CertificateException if not trusted or invalid
}
Example 50
Project: android_libcore-master  File: X509TrustManagerImpl.java View source code
public void checkClientTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {
    if (ax509certificate == null || ax509certificate.length == 0)
        throw new IllegalArgumentException("null or zero-length certificate chain");
    if (s == null || s.length() == 0)
        throw new IllegalArgumentException("null or zero-length authentication type");
    for (int i = 0; i < ax509certificate.length; i++) {
        if (ax509certificate[i].getVersion() != 3) {
            throw new CertificateException();
        }
    }
}
Example 51
Project: cyclos-master  File: ExternalWebServiceHelper.java View source code
private static TrustManager[] getTrustManagers() {
    final TrustManager[] trustManagers = new TrustManager[] { new X509TrustManager() {

        public void checkClientTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {
        }

        public void checkServerTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };
    return trustManagers;
}
Example 52
Project: elexis-3-base-master  File: HCardBrowser.java View source code
public void setProxyPort() {
    if (glnOld == null || !glnOld.equals(gln)) {
        int port = HCardAPI.INSTANCE.getUserProxyPort(gln);
        log.log("getting proxy port for gln:" + gln + " port " + port, Log.DEBUGMSG);
        System.setProperty("https.proxyPort", "" + port);
        glnOld = gln;
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }
        } };
        SSLContext sc;
        try {
            sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    // HostnameVerifier allHostsValid = new HostnameVerifier() {
    // public boolean verify(String arg0, SSLSession arg1) {
    // return true;
    // }
    // };
    //
    // HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    }
}
Example 53
Project: IOCipherServer-master  File: KeyStoreGenerator.java View source code
public static void generateKeyStore(File keyStoreFile, String alias, int keyLength, String password, String cn, String o, String ou, String l, String st, String c) throws Exception {
    final java.security.KeyPairGenerator rsaKeyPairGenerator = java.security.KeyPairGenerator.getInstance("RSA");
    rsaKeyPairGenerator.initialize(keyLength);
    final KeyPair rsaKeyPair = rsaKeyPairGenerator.generateKeyPair();
    // Generate the key store de type JCEKS
    Provider[] ps = Security.getProviders();
    final KeyStore ks = KeyStore.getInstance("BKS");
    ks.load(null);
    final RSAPublicKey rsaPublicKey = (RSAPublicKey) rsaKeyPair.getPublic();
    char[] pw = password.toCharArray();
    final RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) rsaKeyPair.getPrivate();
    final java.security.cert.X509Certificate certificate = makeCertificate(rsaPrivateKey, rsaPublicKey, cn, o, ou, l, st, c);
    final java.security.cert.X509Certificate[] certificateChain = { certificate };
    ks.setKeyEntry(alias, rsaKeyPair.getPrivate(), pw, certificateChain);
    final FileOutputStream fos = new FileOutputStream(keyStoreFile);
    ks.store(fos, pw);
    fos.close();
}
Example 54
Project: languagetool-mirror-master  File: HTTPTools.java View source code
/**
   * For testing, we disable all checks because we use a self-signed certificate on the server
   * side and we want this test to run everywhere without importing the certificate into the JVM's trust store.
   *
   * See http://stackoverflow.com/questions/2893819/telling-java-to-accept-self-signed-ssl-certificate
   */
static void disableCertChecks() throws NoSuchAlgorithmException, KeyManagementException {
    final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    final SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
Example 55
Project: mWater-Android-App-master  File: MWaterServer.java View source code
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws CertificateException {
    byte[] trusted = new byte[] { 56, 78, -127, 94, -29, -46, -31, -88, -72, 25, 7, 12, -45, -74, 51, 73, 16, -30, -7, 23, -63, -4, -77, -125, -60, -3, -70, 111, -93, 79, -82, -49, -29, -38, -92, -11, 121, 82, -53, -56, -14, 18, 94, -24, -31, 122, -75, 2, -63, -82, 25, -9, -91, 103, -62, -80, 86, 73, 9, -72, 121, 38, -33, -47, -34, 26, -79, 66, -123, -34, 48, 63, -84, 24, -107, 64, 60, 11, 2, -54, -98, -56, -92, -25, -73, 19, 9, -62, -104, -95, -116, 109, -124, 20, 105, -33, 121, 1, 48, -66, -61, -101, 8, 89, -90, 84, -100, -50, -70, 124, -70, -41, 44, -52, -43, 56, 63, -11, 127, 18, -42, -94, 29, 44, -101, 84, -82, -127 };
    if (Arrays.equals(certs[0].getSignature(), trusted))
        return;
    throw new CertificateException("Untrusted cert");
}
Example 56
Project: PressGangCCMSREST-master  File: ProcessUtilities.java View source code
/**
     * Checks that a server exists at the specified URL by sending a request to get the headers from the URL.
     *
     * @param serverUrl The URL of the server.
     * @param disableSSLCert
     * @return True if the server exists and got a successful response otherwise false.
     */
public static boolean validateServerExists(final String serverUrl, final boolean disableSSLCert) {
    try {
        if (disableSSLCert) {
            // See http://www.exampledepot.com/egs/javax.net.ssl/TrustAll.html
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                }
            } };
            // Install the all-trusting trust manager
            final SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        }
        URL url = new URL(serverUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("HEAD");
        HttpURLConnection.setFollowRedirects(true);
        int response = connection.getResponseCode();
        if (response == HttpURLConnection.HTTP_MOVED_PERM || response == HttpURLConnection.HTTP_MOVED_TEMP) {
            return validateServerExists(connection.getHeaderField("Location"), disableSSLCert);
        } else {
            return response == HttpURLConnection.HTTP_OK || response == HttpURLConnection.HTTP_BAD_METHOD;
        }
    } catch (Exception e) {
        return false;
    }
}
Example 57
Project: quadprox-mobile-master  File: X509Tunnel.java View source code
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws CertificateException {
    if (certs == null || certs.length < 1) {
        throw new CertificateException("no certs");
    }
    if (certs == null || certs.length > 1) {
        throw new CertificateException("cert path too long");
    }
    PublicKey cakey = cert.getPublicKey();
    boolean ca_match;
    try {
        certs[0].verify(cakey);
        ca_match = true;
    } catch (Exception e) {
        ca_match = false;
    }
    if (!ca_match && !cert.equals(certs[0])) {
        throw new CertificateException("certificate does not match");
    }
}
Example 58
Project: rest.li-master  File: TrustingSocketFactory.java View source code
private static SSLContext createEasySSLContext() {
    try {
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } }, null);
        return context;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 59
Project: ServerAccess-master  File: HTTPResource.java View source code
private static TrustManager[] getConfidingTrustManager() {
    return new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
}
Example 60
Project: useful-java-links-master  File: URLDownloadTests.java View source code
private static void initHTTPSDownload() throws Exception {
    // Create a new trust manager that trust all certificates
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    // Activate the new trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        System.out.print(e.getMessage());
    }
}
Example 61
Project: wildfly-core-master  File: TrustAndStoreTrustManager.java View source code
public static boolean isSubjectInClientCertChain(String rfc2253Name) {
    if (rfc2253Name != null) {
        synchronized (CLIENT_CERTS_LIST) {
            for (X509Certificate cert : CLIENT_CERTS_LIST) {
                if (rfc2253Name.equals(cert.getSubjectX500Principal().getName())) {
                    return true;
                }
            }
        }
    }
    return false;
}
Example 62
Project: wildfly-master  File: TrustAndStoreTrustManager.java View source code
/**
     * Trust all certificates and add them to the {@link #clientCertsList}.
     *
     * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[], java.lang.String)
     */
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    if (chain != null && chain.length > 0) {
        // if the CLIENT_CERTS_LIST is getting too long, clear it
        synchronized (clientCertsList) {
            if (clientCertsList.size() > 50) {
                clientCertsList.clear();
            }
            Collections.addAll(clientCertsList, chain);
        }
    }
}
Example 63
Project: android-15-master  File: X509TrustManagerImpl.java View source code
public void checkClientTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {
    if (ax509certificate == null || ax509certificate.length == 0)
        throw new IllegalArgumentException("null or zero-length certificate chain");
    if (s == null || s.length() == 0)
        throw new IllegalArgumentException("null or zero-length authentication type");
    for (int i = 0; i < ax509certificate.length; i++) {
        if (ax509certificate[i].getVersion() != 3) {
            throw new CertificateException();
        }
    }
}
Example 64
Project: android-bankdroid-master  File: CertPinningTrustManager.java View source code
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
    for (X509Certificate certificate : chain) {
        byte[] publicKey = certificate.getPublicKey().getEncoded();
        for (Certificate pinnedCert : certificates) {
            if (Arrays.equals(publicKey, pinnedCert.getPublicKey().getEncoded())) {
                return;
            }
        }
    }
    throw new CertificateException(host == null ? "Server certificate not trusted." : String.format("Server certificate not trusted for host: %s.", host));
}
Example 65
Project: android-libcore64-master  File: X509TrustManagerImpl.java View source code
public void checkClientTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {
    if (ax509certificate == null || ax509certificate.length == 0)
        throw new IllegalArgumentException("null or zero-length certificate chain");
    if (s == null || s.length() == 0)
        throw new IllegalArgumentException("null or zero-length authentication type");
    for (int i = 0; i < ax509certificate.length; i++) {
        if (ax509certificate[i].getVersion() != 3) {
            throw new CertificateException();
        }
    }
}
Example 66
Project: android-sdk-sources-for-api-level-23-master  File: X509TrustManagerImpl.java View source code
public void checkClientTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {
    if (ax509certificate == null || ax509certificate.length == 0)
        throw new IllegalArgumentException("null or zero-length certificate chain");
    if (s == null || s.length() == 0)
        throw new IllegalArgumentException("null or zero-length authentication type");
    for (int i = 0; i < ax509certificate.length; i++) {
        if (ax509certificate[i].getVersion() != 3) {
            throw new CertificateException();
        }
    }
}
Example 67
Project: android_platform_libcore-master  File: X509TrustManagerImpl.java View source code
public void checkClientTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {
    if (ax509certificate == null || ax509certificate.length == 0)
        throw new IllegalArgumentException("null or zero-length certificate chain");
    if (s == null || s.length() == 0)
        throw new IllegalArgumentException("null or zero-length authentication type");
    for (int i = 0; i < ax509certificate.length; i++) {
        if (ax509certificate[i].getVersion() != 3) {
            throw new CertificateException();
        }
    }
}
Example 68
Project: ant-master  File: TrustManager.java View source code
public static SSLSocketFactory getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final X509TrustManager[] trustAllCerts = new X509TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        return sslSocketFactory;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 69
Project: AppWorkUtils-master  File: CryptServiceProvider.java View source code
@Override
protected TrustManager[] engineGetTrustManagers() {
    return new TrustManager[] { new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };
}
Example 70
Project: ari-toolkit-master  File: TmchCertificateRevokedExceptionTest.java View source code
@Test
public void shouldReturnCorrectMessage() {
    mockStatic(ErrorPkg.class);
    X509Certificate mockCertificate = mock(X509Certificate.class);
    when(ErrorPkg.getMessage("tmch.smd.cert.revoked", "<<cert-detailed-msg>>", mockCertificate)).thenReturn("message");
    TmchCertificateRevokedException exception = new TmchCertificateRevokedException(mockCertificate);
    assertThat(exception.getMessage(), is("message"));
}
Example 71
Project: ARTPart-master  File: X509TrustManagerImpl.java View source code
public void checkClientTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {
    if (ax509certificate == null || ax509certificate.length == 0)
        throw new IllegalArgumentException("null or zero-length certificate chain");
    if (s == null || s.length() == 0)
        throw new IllegalArgumentException("null or zero-length authentication type");
    for (int i = 0; i < ax509certificate.length; i++) {
        if (ax509certificate[i].getVersion() != 3) {
            throw new CertificateException();
        }
    }
}
Example 72
Project: AsyncOkHttp-master  File: CustomSSLSocketFactoryCreator.java View source code
public SSLSocketFactory create() {
    SSLSocketFactory sslSocketFactory = null;
    X509TrustManager tm = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    try {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, new TrustManager[] { tm }, null);
        sslSocketFactory = sc.getSocketFactory();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return sslSocketFactory;
}
Example 73
Project: atlas-lb-master  File: JcaCertStore.java View source code
private static Collection convertCerts(Collection collection) throws CertificateEncodingException {
    List list = new ArrayList(collection.size());
    for (Iterator it = collection.iterator(); it.hasNext(); ) {
        Object o = it.next();
        if (o instanceof X509Certificate) {
            X509Certificate cert = (X509Certificate) o;
            try {
                list.add(new X509CertificateHolder(cert.getEncoded()));
            } catch (IOException e) {
                throw new CertificateEncodingException("unable to read encoding: " + e.getMessage());
            }
        } else {
            list.add((X509CertificateHolder) o);
        }
    }
    return list;
}
Example 74
Project: bnd-master  File: HttpsUtil.java View source code
static void disableServerVerification(URLConnection connection) throws GeneralSecurityException {
    if (!(connection instanceof HttpsURLConnection))
        return;
    HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }
    } };
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustAllCerts, new SecureRandom());
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    httpsConnection.setSSLSocketFactory(sslSocketFactory);
    HostnameVerifier trustAnyHost = new HostnameVerifier() {

        public boolean verify(String string, SSLSession session) {
            return true;
        }
    };
    httpsConnection.setHostnameVerifier(trustAnyHost);
}
Example 75
Project: browsermob-proxy-master  File: ThumbprintUtil.java View source code
/**
	 * Generates a SHA1 thumbprint of a certificate for long-term mapping.
	 * @param cert
	 * @return
	 * @throws java.security.cert.CertificateEncodingException
	 */
public static String getThumbprint(final X509Certificate cert) throws CertificateEncodingException {
    if (cert == null) {
        return null;
    }
    byte[] rawOctets = cert.getEncoded();
    SHA1Digest digest = new SHA1Digest();
    byte[] digestOctets = new byte[digest.getDigestSize()];
    digest.update(rawOctets, 0, rawOctets.length);
    digest.doFinal(digestOctets, 0);
    return new String(Base64.encode(digestOctets));
}
Example 76
Project: bugvm-master  File: JcaCertStore.java View source code
private static Collection convertCerts(Collection collection) throws CertificateEncodingException {
    List list = new ArrayList(collection.size());
    for (Iterator it = collection.iterator(); it.hasNext(); ) {
        Object o = it.next();
        if (o instanceof X509Certificate) {
            X509Certificate cert = (X509Certificate) o;
            try {
                list.add(new X509CertificateHolder(cert.getEncoded()));
            } catch (IOException e) {
                throw new CertificateEncodingException("unable to read encoding: " + e.getMessage());
            }
        } else {
            list.add((X509CertificateHolder) o);
        }
    }
    return list;
}
Example 77
Project: caelum-stella-master  File: TokenKeyStoreForWindows.java View source code
public CertificateAndPrivateKey getCertificateFor(String alias) {
    try {
        X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
        PrivateKey privateKey = (PrivateKey) ks.getKey(alias, senhaDoCertificado.toCharArray());
        return new CertificateAndPrivateKey(certificate, privateKey);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 78
Project: canl-java-master  File: RolloverTest.java View source code
@Test
public void test() throws Exception {
    OpensslCertChainValidator validator = new OpensslCertChainValidator("src/test/resources/rollover/openssl-trustdir");
    X509Certificate[] cert1 = CertificateUtils.loadCertificateChain(new FileInputStream("src/test/resources/rollover/user-from-old.pem"), Encoding.PEM);
    ValidationResult result = validator.validate(cert1);
    Assert.assertTrue(result.toString(), result.isValid());
    X509Certificate[] cert2 = CertificateUtils.loadCertificateChain(new FileInputStream("src/test/resources/rollover/user-from-new.pem"), Encoding.PEM);
    ValidationResult result2 = validator.validate(cert2);
    Assert.assertTrue(result2.toString(), result2.isValid());
}
Example 79
Project: cas-master  File: X509SubjectDNPrincipalResolverTests.java View source code
@Test
public void verifyResolvePrincipalInternal() {
    final X509CertificateCredential c = new X509CertificateCredential(new X509Certificate[] { VALID_CERTIFICATE });
    c.setCertificate(VALID_CERTIFICATE);
    assertEquals(VALID_CERTIFICATE.getSubjectDN().getName(), this.resolver.resolve(c, CoreAuthenticationTestUtils.getPrincipal(), new SimpleTestUsernamePasswordAuthenticationHandler()).getId());
}
Example 80
Project: codedx-plugin-master  File: FingerprintStrategy.java View source code
public CertificateAcceptance checkAcceptance(Certificate genericCert, CertificateException certError) {
    if (genericCert instanceof X509Certificate) {
        X509Certificate cert = (X509Certificate) genericCert;
        try {
            String certFingerprint = HashUtil.toHexString(HashUtil.getSHA1(cert.getEncoded()));
            logger.info("Certificate fingerprint:  " + certFingerprint.toUpperCase());
            logger.info("User-entered fingerprint: " + fingerprint.toUpperCase());
            if (certFingerprint.toUpperCase().equals(fingerprint.toUpperCase())) {
                return CertificateAcceptance.ACCEPT_PERMANENTLY;
            }
        } catch (CertificateEncodingException exception) {
            logger.warning("Problem reading certificate: " + exception);
            exception.printStackTrace();
        }
    } else {
        logger.warning("Certificate presented was not X509: " + genericCert);
    }
    return CertificateAcceptance.REJECT;
}
Example 81
Project: dex2jar-master  File: SunJarSignImpl.java View source code
/** Write a .RSA file with a digital signature. */
@SuppressWarnings("all")
protected void writeSignatureBlock(byte[] signature, OutputStream out) throws IOException {
    try {
        SignerInfo signerInfo = new SignerInfo(new X500Name(cert.getIssuerX500Principal().getName()), cert.getSerialNumber(), AlgorithmId.get(digestAlg), AlgorithmId.get("RSA"), signature);
        PKCS7 pkcs7 = new PKCS7(new AlgorithmId[] { AlgorithmId.get(digestAlg) }, new ContentInfo(ContentInfo.DATA_OID, null), new X509Certificate[] { cert }, new SignerInfo[] { signerInfo });
        pkcs7.encodeSignedData(out);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}
Example 82
Project: digidoc4j-master  File: TokenAlgorithmSupportTest.java View source code
@Test
public void getDefaultDigestAlgorithm_shouldReturnSha256() throws Exception {
    PKCS12SignatureToken testSignatureToken = new PKCS12SignatureToken("testFiles/signout.p12", "test".toCharArray());
    X509Certificate signCert = testSignatureToken.getCertificate();
    DigestAlgorithm digestAlgorithm = TokenAlgorithmSupport.determineSignatureDigestAlgorithm(signCert);
    Assert.assertEquals(DigestAlgorithm.SHA256, digestAlgorithm);
}
Example 83
Project: DTE-master  File: TestAutenticacion.java View source code
/**
	 * @param args
	 */
public static void main(String[] args) {
    if (args.length != 2) {
        System.err.println("Utilice: java cl.nic.dte.examples.TestAutenticacion " + "<certDigital.p12> <password>");
        System.exit(-1);
    }
    try {
        // leo certificado y llave privada del archivo pkcs12
        // leo certificado y llave privada del archivo pkcs12
        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(new FileInputStream(args[0]), args[1].toCharArray());
        String alias = ks.aliases().nextElement();
        System.out.println("Usando certificado " + alias + " del archivo PKCS12: " + args[0]);
        X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
        PrivateKey key = (PrivateKey) ks.getKey(alias, args[1].toCharArray());
        ConexionSii con = new ConexionSii();
        String token = con.getToken(key, cert);
        System.out.println("\n\nToken: " + token);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 84
Project: factura-electronica-master  File: PublicKeyLoader.java View source code
public void setX509Certificate(InputStream crtInputStream) {
    try {
        this.key = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(crtInputStream);
    } catch (CertificateException e) {
        throw new KeyException("Error al obtener el certificado x.509. La codificación puede ser incorrecta.", e.getCause());
    }
}
Example 85
Project: fdroidclient-master  File: CustomKeySigner.java View source code
/** KeyStore-type agnostic.  This method will sign the zip file, automatically handling JKS or BKS keystores. */
public static void signZip(ZipSigner zipSigner, String keystorePath, char[] keystorePw, String certAlias, char[] certPw, String signatureAlgorithm, String inputZipFilename, String outputZipFilename) throws Exception {
    zipSigner.issueLoadingCertAndKeysProgressEvent();
    KeyStore keystore = KeyStoreFileManager.loadKeyStore(keystorePath, keystorePw);
    Certificate cert = keystore.getCertificate(certAlias);
    X509Certificate publicKey = (X509Certificate) cert;
    Key key = keystore.getKey(certAlias, certPw);
    PrivateKey privateKey = (PrivateKey) key;
    zipSigner.setKeys("custom", publicKey, privateKey, signatureAlgorithm, null);
    zipSigner.signZip(inputZipFilename, outputZipFilename);
}
Example 86
Project: gizmo-master  File: ThumbprintUtil.java View source code
/**
	 * Generates a SHA1 thumbprint of a certificate for long-term mapping.
	 * @param cert
	 * @return
	 * @throws CertificateEncodingException
	 */
public static String getThumbprint(final X509Certificate cert) throws CertificateEncodingException {
    if (cert == null) {
        return null;
    }
    byte[] rawOctets = cert.getEncoded();
    SHA1Digest digest = new SHA1Digest();
    byte[] digestOctets = new byte[digest.getDigestSize()];
    digest.update(rawOctets, 0, rawOctets.length);
    digest.doFinal(digestOctets, 0);
    return new String(Base64.encode(digestOctets));
}
Example 87
Project: intellij-community-master  File: ShowCertificateInfoAction.java View source code
@Override
public void actionPerformed(final AnActionEvent e) {
    try {
        CertificateManager manager = CertificateManager.getInstance();
        List<X509Certificate> certificates = manager.getCustomTrustManager().getCertificates();
        if (certificates.isEmpty()) {
            Messages.showInfoMessage(String.format("Key store '%s' is empty", manager.getCacertsPath()), "No Certificates Available");
        } else {
            CertificateWarningDialog dialog = CertificateWarningDialog.createUntrustedCertificateWarning(certificates.get(0));
            LOG.debug("Accepted: " + dialog.showAndGet());
        }
    } catch (Exception logged) {
        LOG.error(logged);
    }
}
Example 88
Project: irma_future_id-master  File: JcaCertStore.java View source code
private static Collection convertCerts(Collection collection) throws CertificateEncodingException {
    List list = new ArrayList(collection.size());
    for (Iterator it = collection.iterator(); it.hasNext(); ) {
        Object o = it.next();
        if (o instanceof X509Certificate) {
            X509Certificate cert = (X509Certificate) o;
            try {
                list.add(new X509CertificateHolder(cert.getEncoded()));
            } catch (IOException e) {
                throw new CertificateEncodingException("unable to read encoding: " + e.getMessage());
            }
        } else {
            list.add((X509CertificateHolder) o);
        }
    }
    return list;
}
Example 89
Project: java-csp-master  File: TestLoadKeyStore.java View source code
@Test
public void testLoalCertificates() throws Exception {
    KeyStore keyStore = java.security.KeyStore.getInstance(STORE_NAME, PROVIDER_NAME);
    keyStore.load(null, null);
    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
        LOGGER.debug("Ключ {}" + "\n\tSubject {}" + "\n\tS/N     {}" + "\n\tIssuer  {}", new Object[] { alias, cert.getSubjectDN().getName(), cert.getSerialNumber().toString(16), cert.getIssuerDN().getName() });
    }
}
Example 90
Project: jxse-master  File: DefaultSecureTCPMessageTest.java View source code
@Override
protected void run() {
    try {
        PeerID alicePeerID = aliceManager.getNetPeerGroup().getPeerID();
        PeerID bobPeerID = bobManager.getNetPeerGroup().getPeerID();
        PSEMembershipService alicePSEMembershipService = (PSEMembershipService) aliceManager.getNetPeerGroup().getMembershipService();
        PSEMembershipService bobPSEMembershipService = (PSEMembershipService) bobManager.getNetPeerGroup().getMembershipService();
        PSEConfig alicePSEConfig = alicePSEMembershipService.getPSEConfig();
        PSEConfig bobPSEConfig = bobPSEMembershipService.getPSEConfig();
        X509Certificate aliceCertificate = alicePSEConfig.getTrustedCertificate(alicePeerID);
        X509Certificate bobCertificate = bobPSEConfig.getTrustedCertificate(bobPeerID);
        alicePSEConfig.setTrustedCertificate(bobPeerID, bobCertificate);
        bobPSEConfig.setTrustedCertificate(alicePeerID, aliceCertificate);
        testColocatedPeerBidiPipeComms(true);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Example 91
Project: karate-master  File: HttpUtils.java View source code
public static SSLContext getSslContext(String algorithm) {
    TrustManager[] certs = new TrustManager[] { new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };
    SSLContext ctx = null;
    if (algorithm == null) {
        algorithm = "TLS";
    }
    try {
        ctx = SSLContext.getInstance(algorithm);
        ctx.init(null, certs, new SecureRandom());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return ctx;
}
Example 92
Project: ldaptive-master  File: X509CertificatesCredentialReader.java View source code
@Override
public X509Certificate[] read(final InputStream is, final String... params) throws IOException, GeneralSecurityException {
    final CertificateFactory cf = CertificateFactory.getInstance("X.509");
    final List<X509Certificate> certList = new ArrayList<>();
    final InputStream bufIs = getBufferedInputStream(is);
    while (bufIs.available() > 0) {
        final X509Certificate cert = (X509Certificate) cf.generateCertificate(bufIs);
        if (cert != null) {
            certList.add(cert);
        }
    }
    return certList.toArray(new X509Certificate[certList.size()]);
}
Example 93
Project: lmis-moz-mobile-master  File: LMISRestManagerTest.java View source code
@Test
public void shouldVerify() throws Exception {
    SSLSession sslSession = mock(SSLSession.class);
    X509Certificate certificate = mock(X509Certificate.class);
    Principal principal = new Principal() {

        @Override
        public String getName() {
            return "CN=lmis.cmam.gov.mz";
        }
    };
    when(sslSession.getPeerCertificates()).thenReturn(new Certificate[] { certificate });
    when(certificate.getSubjectDN()).thenReturn(principal);
    LMISRestManagerMock.mockClient = mock(Client.class);
    LMISRestManagerMock lmisRestManagerMock = new LMISRestManagerMock(RuntimeEnvironment.application);
    lmisRestManagerMock.superGetSSLClient();
    assertTrue(lmisRestManagerMock.okHttpClient.getHostnameVerifier().verify("whateverName", sslSession));
}
Example 94
Project: lyo.client-master  File: OAuthClient.java View source code
// not recommended for production environments!
// needed if the server uses self-signed certificates, however
private static void disableCertificateValidatation(HttpClient client) {
    try {
        final SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] { new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } }, new java.security.SecureRandom());
        final SSLSocketFactory socketFactory = new SSLSocketFactory(sc, new X509HostnameVerifier() {

            public void verify(String string, SSLSocket ssls) throws IOException {
            }

            public void verify(String string, X509Certificate xc) throws SSLException {
            }

            public void verify(String string, String[] strings, String[] strings1) throws SSLException {
            }

            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        });
        final Scheme https = new Scheme("https", 443, socketFactory);
        client.getConnectionManager().getSchemeRegistry().register(https);
    } catch (GeneralSecurityException e) {
    }
}
Example 95
Project: mobilib-master  File: MblSSLCertificateUtils.java View source code
// reference: http://stackoverflow.com/questions/1201048/allowing-java-to-use-an-untrusted-certificate-for-ssl-https-connection
public static javax.net.ssl.SSLSocketFactory getSSLSocketFactoryIgnoreSSLCertificate() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        return sc.getSocketFactory();
    } catch (Exception ignored) {
        return null;
    }
}
Example 96
Project: mockserver-master  File: KeyStoreFactoryTest.java View source code
@Test
public void shouldCreateClientCertWithPositiveSerialNumber() throws Exception {
    X509Certificate caCert = this.keyStoreFactory.createCACert(caKeyPair.getPublic(), caKeyPair.getPrivate());
    KeyPair clientKeyPair = this.keyStoreFactory.generateKeyPair(1024);
    X509Certificate clientCert = this.keyStoreFactory.createClientCert(clientKeyPair.getPublic(), caCert, this.caKeyPair.getPrivate(), this.caKeyPair.getPublic(), "example.com", new String[] { "www.example.com" }, null);
    assertTrue("The client cert serial number is non-negative", clientCert.getSerialNumber().compareTo(BigInteger.ZERO) > 0);
}
Example 97
Project: MVP-master  File: TrustManager.java View source code
public static SSLSocketFactory getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final X509TrustManager[] trustAllCerts = new X509TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        return sslSocketFactory;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 98
Project: nutzwx-master  File: WxPaySSL.java View source code
public static SSLSocketFactory buildSSL(File file, String password) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(file);
    try {
        keyStore.load(instream, password.toCharArray());
    } finally {
        instream.close();
    }
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keyStore);
    TrustManager[] tms = { new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, password.toCharArray());
    SSLContext sc = SSLContext.getInstance("TLSv1");
    sc.init(kmf.getKeyManagers(), tms, new SecureRandom());
    return sc.getSocketFactory();
}
Example 99
Project: offspring-master  File: TestX509CertificateVerify.java View source code
@Test
public void testValidCertificate() {
    List<File> files = new ArrayList<File>(Arrays.asList(new File[] { jar1, jar2 }));
    X509Certificate certificate = X509CertificateFile.getCertificate(cert1);
    assertEquals(files.size(), 2);
    assertEquals(files.get(0), jar1);
    assertEquals(files.get(1), jar2);
    verifier.verify(files, certificate);
    assertEquals(files.size(), 1);
    assertEquals(files.get(0), jar2);
}
Example 100
Project: oobd-master  File: JcaCertStore.java View source code
private static Collection convertCerts(Collection collection) throws CertificateEncodingException {
    List list = new ArrayList(collection.size());
    for (Iterator it = collection.iterator(); it.hasNext(); ) {
        Object o = it.next();
        if (o instanceof X509Certificate) {
            X509Certificate cert = (X509Certificate) o;
            try {
                list.add(new X509CertificateHolder(cert.getEncoded()));
            } catch (IOException e) {
                throw new CertificateEncodingException("unable to read encoding: " + e.getMessage());
            }
        } else {
            list.add((X509CertificateHolder) o);
        }
    }
    return list;
}
Example 101
Project: open-ecard-master  File: SignatureUsageWrapper.java View source code
public boolean hasUsage(X509Certificate x509cert) {
    if (keyUsage != null && extendedKeyUsage != null) {
        return (keyUsage.hasUsage(x509cert) & extendedKeyUsage.hasUsage(x509cert));
    } else if (keyUsage != null) {
        return keyUsage.hasUsage(x509cert);
    } else if (extendedKeyUsage != null) {
        return extendedKeyUsage.hasUsage(x509cert);
    }
    return false;
}