Android平台访问https 双向认证(下)




 访问https双向认证两种方式


public static void httpsRequest(Context c) {
		try {
			String path = "https://localhost:8443/123.html";

			BasicHttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params,
					HTTP.DEFAULT_CONTENT_CHARSET);
			HttpProtocolParams.setUseExpectContinue(params, true);

			SSLSocketFactory.getSocketFactory().setHostnameVerifier(
					new AllowAllHostnameVerifier());

			SchemeRegistry schReg = new SchemeRegistry();

			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			// 出错:因为使用了不被系统承认的自定义证书:No peer certificate 。

			// schReg.register(new Scheme("https",SSLSocketFactory.getSocketFactory(), 443));

			schReg.register(new Scheme("https", SSLTrustAllSocketFactory
			 		.getSocketFactory(c), 443));
			ClientConnectionManager connMgr = new ThreadSafeClientConnManager(
					params, schReg);
			DefaultHttpClient client = new DefaultHttpClient(connMgr, params);

			HttpGet request = new HttpGet(path);

			HttpResponse httpResponse = client.execute(request);
			int responseCode = httpResponse.getStatusLine().getStatusCode();
			String message = httpResponse.getStatusLine().getReasonPhrase();
			HttpEntity entity = httpResponse.getEntity();
			if (responseCode == 200 && entity != null) {
				Log.e("log", entity.toString());
			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static class SSLTrustAllSocketFactory extends SSLSocketFactory {

		private static final String TAG = "SSLTrustAllSocketFactory";
		private SSLContext mCtx;

        public SSLTrustAllSocketFactory(KeyStore truststore,Context context) throws Throwable {
			super(truststore);
			try {
				// Client should authenticate itself with the valid certificate to Server.
	        	InputStream clientStream = context.getResources().openRawResource(R.raw.client);
	        	char[] password = "123456".toCharArray();
				KeyStore keyStore = KeyStore.getInstance("PKCS12");
		        keyStore.load(clientStream, password);

	            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	            keyManagerFactory.init(keyStore, password);
	            
	            
		        // Client should also add the CA certificate obtained from server and create TrustManager from it for the client to validate the 
	            // identity of the server.
		        KeyStore trustStore  = KeyStore.getInstance("BKS");
		        InputStream instream = null;
		        instream = context.getResources().openRawResource(R.raw.newserver);
//		        trustStore.setCertificateEntry("dd", certificateFactory.generateCertificate(instream));
		        try {
		            trustStore.load(instream, "123456".toCharArray());
		        } catch (Exception e) {
		            e.printStackTrace();
		        } finally {
		            try { instream.close(); } catch (Exception ignore) {}
		        }            

	            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
	            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
	            tmf.init(trustStore);
	            
                    mCtx = SSLContext.getInstance("TLS");
		    mCtx.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);
				

//		   setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			} catch (Exception ex) {
			}
		}

		@Override
		public Socket createSocket(Socket socket, String host, int port,
				boolean autoClose) throws IOException, UnknownHostException {
			return mCtx.getSocketFactory().createSocket(socket, host, port,
					autoClose);
		}

		@Override
		public Socket createSocket() throws IOException {
			return mCtx.getSocketFactory().createSocket();
		}

		public static SSLSocketFactory getSocketFactory(Context c) {
			try {
			
				SSLSocketFactory factory = new SSLTrustAllSocketFactory(
						null,c);
				return factory;
			} catch (Throwable e) {
				Log.d(TAG, e.getMessage());
				e.printStackTrace();
			}
			return null;
		}

	}



	public static void https2(Context context) {
		try {
			String path = "https://192.168.0.102:8443/123.html";

			BasicHttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params,
					HTTP.DEFAULT_CONTENT_CHARSET);
			HttpProtocolParams.setUseExpectContinue(params, true);

			SchemeRegistry schReg = new SchemeRegistry();

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

			InputStream clientStream = context.getResources().openRawResource(
					R.raw.client);
			char[] password = "123456".toCharArray();
			KeyStore keyStore = KeyStore.getInstance("PKCS12");
			keyStore.load(clientStream, password);

			KeyManagerFactory keyManagerFactory = KeyManagerFactory
					.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			keyManagerFactory.init(keyStore, password);

			KeyStore trustStore = KeyStore.getInstance("BKS");
			InputStream instream = null;
			instream = context.getResources().openRawResource(R.raw.newserver);
			// trustStore.setCertificateEntry("dd",
			// certificateFactory.generateCertificate(instream));
			try {
				trustStore.load(instream, "123456".toCharArray());
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					instream.close();
				} catch (Exception ignore) {
				}
			}

			String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
			TrustManagerFactory tmf = TrustManagerFactory
					.getInstance(tmfAlgorithm);
			tmf.init(trustStore);

			SSLSocketFactory myssl = new SSLSocketFactory(keyStore, "123456",
					trustStore);
			myssl.setHostnameVerifier((new AllowAllHostnameVerifier()));
			schReg.register(new Scheme("https", myssl, 443));
			ClientConnectionManager connMgr = new ThreadSafeClientConnManager(
					params, schReg);
			DefaultHttpClient client = new DefaultHttpClient(connMgr, params);

			HttpGet request = new HttpGet(path);

			HttpResponse httpResponse = client.execute(request);
			int responseCode = httpResponse.getStatusLine().getStatusCode();
			String message = httpResponse.getStatusLine().getReasonPhrase();
			HttpEntity entity = httpResponse.getEntity();
			if (responseCode == 200 && entity != null) {
				Log.e("log", entity.toString() + "dddddddddd");
			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeyManagementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnrecoverableKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeyStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (CertificateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}


 
  


你可能感兴趣的:(https双向认证,android提高篇)