Example usage for javax.net.ssl X509TrustManager X509TrustManager

List of usage examples for javax.net.ssl X509TrustManager X509TrustManager

Introduction

In this page you can find the example usage for javax.net.ssl X509TrustManager X509TrustManager.

Prototype

X509TrustManager

Source Link

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }//  w w  w  . j av a 2s .co m

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

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

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    URL url = new URL("https://hostname/index.html");
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }/*from w ww  .j  ava 2s. c om*/

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

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

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    URL url = new URL("https://hostname/index.html");
}

From source file:com.logic.test.FTPSLogic.java

public static void main(String[] args) {
    String serverAdress = "62.2.176.167";
    String username = "RLSFTPRead";
    String password = "ftp4rls";
    int port = 990;
    FTPSClient ftpsClient = new FTPSClient("TLS", true);
    String remoteFile = "REM - Persons Extract.csv";
    File localFile = new File("Persons Extract.csv");

    try {/*from  ww  w . j a v a2  s .c  o m*/
        TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

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

        ftpsClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

        //ftpsClient.setTrustManager(trustManager[0]);
        //KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        //kmf.init(null, null);
        //KeyManager km = kmf.getKeyManagers()[0];

        //ftpsClient.setKeyManager(km);
        ftpsClient.setBufferSize(1024 * 1024);
        ftpsClient.setConnectTimeout(100000);
        ftpsClient.connect(InetAddress.getByName(serverAdress), port);
        ftpsClient.setSoTimeout(100000);

        if (ftpsClient.login(username, password)) {
            ftpsClient.execPBSZ(0);
            ftpsClient.execPROT("P");
            ftpsClient.changeWorkingDirectory("/");
            ftpsClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpsClient.enterLocalPassiveMode();

            //ftpsClient.retrieveFile(remoteFile, new FileOutputStream(localFile));
            for (FTPFile file : ftpsClient.listFiles()) {
                System.out.println("Nom " + file.getName());
            }

        }
    } catch (SocketException e) {
        ;
    } catch (UnknownHostException e) {
        ;
    } catch (IOException e) {
        ;
    } catch (Exception e) {
        ;
    } finally {
        try {
            ftpsClient.logout();
        } catch (Exception e2) {
        }

        try {
            ftpsClient.disconnect();
        } catch (Exception e2) {
        }
    }
}

From source file:com.cloudhopper.httpclient.util.HttpPostMain.java

static public void main(String[] args) throws Exception {
    ////from  w ww  .ja  v a  2 s.com
    // target urls
    //
    String strURL = "http://209.226.31.233:9009/SendSmsService/b98183b99a1f473839ce569c78b84dbd";

    // Username: Twitter
    // Password: Twitter123

    TrustManager easyTrustManager = new X509TrustManager() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

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

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

    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);

    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", sf, 443);

    //SchemeRegistry sr = new SchemeRegistry();
    //sr.register(http);
    //sr.register(https);

    // create and initialize scheme registry
    //SchemeRegistry schemeRegistry = new SchemeRegistry();
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    //ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    //cm.setMaxTotalConnections(1);

    DefaultHttpClient client = new DefaultHttpClient();

    client.getConnectionManager().getSchemeRegistry().register(https);

    //        for (int i = 0; i < 1; i++) {
    //
    // create a new ticket id
    //
    //String ticketId = TicketUtil.generate(1, System.currentTimeMillis());

    /**
    StringBuilder string0 = new StringBuilder(200)
        .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
        .append("<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n")
        .append("       <S:Header>\n")
        .append("               <ns3:TransactionID xmlns:ns4=\"http://vmp.vzw.com/schema\"\n")
        .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\">" + ticketId + "</ns3:TransactionID>\n")
        .append("       </S:Header>\n")
        .append("       <S:Body>\n")
        .append("               <ns2:OptinReq xmlns:ns4=\"http://schemas.xmlsoap.org/soap/envelope/\"\n")
        .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\"\n")
        .append("xmlns:ns2=\"http://vmp.vzw.com/schema\">\n")
        .append("                      <ns2:VASPID>twitter</ns2:VASPID>\n")
        .append("                      <ns2:VASID>tm33t!</ns2:VASID>\n")
        .append("                      <ns2:ShortCode>800080008001</ns2:ShortCode>\n")
        .append("                      <ns2:Number>9257089093</ns2:Number>\n")
        .append("                      <ns2:Source>provider</ns2:Source>\n")
        .append("                      <ns2:Message/>\n")
        .append("               </ns2:OptinReq>\n")
        .append("       </S:Body>\n")
        .append("</S:Envelope>");
     */

    // simple send sms
    StringBuilder string1 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
            .append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:loc=\"http://www.csapi.org/schema/parlayx/sms/send/v2_3/local\">\n")
            .append("   <soapenv:Header/>\n").append("   <soapenv:Body>\n").append("      <loc:sendSms>\n")
            .append("         <loc:addresses>tel:+16472260233</loc:addresses>\n")
            .append("         <loc:senderName>6388</loc:senderName>\n")
            .append("         <loc:message>Test Message &</loc:message>\n").append("      </loc:sendSms>\n")
            .append("   </soapenv:Body>\n").append("</soapenv:Envelope>\n");

    // startSmsNotification - place to deliver SMS to

    String req = string1.toString();
    logger.debug("Request XML -> \n" + req);

    HttpPost post = new HttpPost(strURL);

    StringEntity postEntity = new StringEntity(req, "ISO-8859-1");
    postEntity.setContentType("text/xml; charset=\"ISO-8859-1\"");
    post.addHeader("SOAPAction", "\"\"");
    post.setEntity(postEntity);

    long start = System.currentTimeMillis();

    client.getCredentialsProvider().setCredentials(new AuthScope("209.226.31.233", AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("Twitter", "Twitter123"));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local 
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpResponse httpResponse = client.execute(post, localcontext);
    HttpEntity responseEntity = httpResponse.getEntity();

    //
    // was the request OK?
    //
    if (httpResponse.getStatusLine().getStatusCode() != 200) {
        logger.error("Request failed with StatusCode=" + httpResponse.getStatusLine().getStatusCode());
    }

    // get an input stream
    String responseBody = EntityUtils.toString(responseEntity);

    long stop = System.currentTimeMillis();

    logger.debug("----------------------------------------");
    logger.debug("Response took " + (stop - start) + " ms");
    logger.debug(responseBody);
    logger.debug("----------------------------------------");
    //        }

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    client.getConnectionManager().shutdown();
}

From source file:drmaas.sandbox.http.LoginTest.java

public static void main(String[] args) throws Exception {

    //1. For SSL/*from ww  w  . ja  v  a 2s . c om*/
    DefaultHttpClient base = new DefaultHttpClient();
    SSLContext ctx = SSLContext.getInstance("TLS");

    X509TrustManager tm = new X509TrustManager() {
        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

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

    X509HostnameVerifier verifier = new X509HostnameVerifier() {

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

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

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

        @Override
        public boolean verify(String string, SSLSession ssls) {
            return true;
        }
    };

    ctx.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx, verifier);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", 443, ssf));
    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, base.getParams());
    httpclient.setRedirectStrategy(new LaxRedirectStrategy());

    try {
        HttpPost httpost;
        HttpResponse response;
        HttpEntity entity;
        List<Cookie> cookies;
        BufferedReader rd;
        String line;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        //log in
        httpost = new HttpPost("myloginurl");

        nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("login", "Log In"));
        nvps.add(new BasicNameValuePair("os_username", "foo"));
        nvps.add(new BasicNameValuePair("os_password", "foobar"));
        nvps.add(new BasicNameValuePair("os_cookie", "true"));
        nvps.add(new BasicNameValuePair("os_destination", ""));

        httpost.setEntity(new UrlEncodedFormEntity(nvps));
        response = httpclient.execute(httpost);
        System.out.println(response.toString());
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:mitm.common.security.ca.handlers.ejbca.ws.EjbcaWSClient.java

public static void main(String args[]) throws Exception {
    BasicConfigurator.configure();//from  w  ww.j  a v  a2  s  .com

    JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();

    factory.setServiceClass(EjbcaWS.class);
    factory.setAddress("https://192.168.178.113:8443/ejbca/ejbcaws/ejbcaws");
    factory.setServiceName(SERVICE_NAME);

    EjbcaWS client = (EjbcaWS) factory.create();

    Client proxy = ClientProxy.getClient(client);
    HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
    TLSClientParameters tlsClientParameters = new TLSClientParameters();

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

    java.security.KeyStore keyStore = java.security.KeyStore.getInstance("PKCS12");
    InputStream keyInput = new FileInputStream("/home/martijn/temp/superadmin.p12");

    String password = "ejbca";

    keyStore.load(keyInput, password.toCharArray());
    keyInput.close();
    keyManagerFactory.init(keyStore, password.toCharArray());

    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    tlsClientParameters.setDisableCNCheck(true);

    tlsClientParameters.setKeyManagers(keyManagers);

    X509TrustManager trustAll = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
                throws CertificateException {
        }

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

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

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    trustManagerFactory.init(new KeyStoreLoader().loadKeyStore(new File("/home/martijn/temp/truststore.jks"),
            "changeit".toCharArray()));

    tlsClientParameters.setTrustManagers(new TrustManager[] { trustAll });
    //tlsClientParameters.setTrustManagers(trustManagerFactory.getTrustManagers());

    conduit.setTlsClientParameters(tlsClientParameters);

    System.out.println(client.getEjbcaVersion());

    UserDataVOWS userData = new UserDataVOWS();

    userData.setEmail("test@example.com");
    userData.setUsername("test@example.com");
    //userData.setPassword("test@example.com");
    userData.setSubjectDN("CN=test@example.com");
    userData.setSubjectAltName("rfc822Name=test@example.com");
    userData.setEndEntityProfileName("test");
    userData.setCaName("AdminCA1");
    userData.setCertificateProfileName("ENDUSER");
    userData.setStatus(EJBCAConst.STATUS_NEW);
    userData.setTokenType(EJBCAConst.TOKEN_TYPE_USERGENERATED);

    try {
        //client.editUser(userData);

        SecurityFactory securityFactory = SecurityFactoryFactory.getSecurityFactory();

        SecureRandom randomSource = securityFactory.createSecureRandom();

        KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA");

        keyPairGenerator.initialize(2048, randomSource);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X500PrincipalBuilder builder = new X500PrincipalBuilder();

        builder.setCommonName("john doe");
        builder.setEmail("test@example.com");

        PKCS10CertificationRequestBuilder requestBuilder = new PKCS10CertificationRequestBuilder(
                X500PrincipalUtils.toX500Name(builder.buildPrincipal()),
                SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

        PKCS10CertificationRequest pkcs10 = requestBuilder
                .build(getContentSigner("SHA1WithRSA", keyPair.getPrivate()));

        String base64PKCS10 = Base64Utils.encode(pkcs10.getEncoded());

        CertificateResponse certificateResponse = client.certificateRequest(userData, base64PKCS10,
                EJBCAConst.CERT_REQ_TYPE_PKCS10, null, EJBCAConst.RESPONSETYPE_CERTIFICATE);

        if (certificateResponse != null && certificateResponse.getData() != null) {
            /*
             * The result is a base64 encoded certificate 
             */
            Collection<X509Certificate> certificates = CertificateUtils.readX509Certificates(
                    new ByteArrayInputStream(Base64.decode(certificateResponse.getData())));

            if (CollectionUtils.isNotEmpty(certificates)) {
                for (X509Certificate certificate : certificates) {
                    System.out.println(certificate);
                }
            } else {
                System.out.println("No certificates found");
            }
        } else {
            System.out.println("certificateResponse is empty");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

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;
        }/*from w w w .  ja  v  a2 s.  c  om*/

        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;
    }
}

From source file:Main.java

/**
 * Get trust manager to permit all of certifications.
 * @return TrustManager array with one X509TrustManager element
 *//* www. j a  v  a  2  s  . co  m*/
private static TrustManager[] getTrustAllCerts() {
    return 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 X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }
    } };
}

From source file:Main.java

public static void disableSSLCertificateChecking() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }/*from ww  w.j a  va 2s.c  o m*/

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

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // Not implemented
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("TLS");

        sc.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

/**
 * Trust every server - dont check for any certificate
 *//*w  ww .  ja v  a 2  s . co m*/
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[] {};
        }

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

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

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

        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub

        }
    } };

    // 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();
    }
}