android https之三
16lz
2021-12-04
android https之一
android https之二
android https之三
android https之二
android https之三
private static void installCert(String host, int port, String passwd,String sslProtocol) {try {String trustStorePath = System.getProperty("javax.net.ssl.trustStore");// File keystoreFile = new File(trustStorePath);// 由于android权限原因,无法读取trustStorePath="//system/etc/security/cacerts.bks"文件,此处由sdcard代替File keystoreFile = new File("/sdcard/cacerts.bks");InputStream in = new FileInputStream(keystoreFile);KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());ks.load(in, passwd.toCharArray());in.close();SSLContext context = SSLContext.getInstance(sslProtocol);TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());tmf.init(ks);X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);context.init(null, new TrustManager[] { tm }, null);javax.net.ssl.SSLSocketFactory factory = context.getSocketFactory();boolean istrusted = false;try {SSLSocket socket = (SSLSocket) factory.createSocket(host, port);socket.setSoTimeout(50000);socket.startHandshake();socket.close();istrusted = true;} catch (SSLException e) {Log.i("xx", e.getMessage());istrusted = false;}if (!istrusted) {X509Certificate[] chain = tm.chain;if (chain == null) {return;}ks.setCertificateEntry(host + "_" + 0, chain[0]);// 如果想更改新密码,这个passwd替换成新密码即可ks.store(new FileOutputStream(new File("/sdcard/cacerts.bks")),passwd.toCharArray());}} catch (FileNotFoundException e) {Log.e("xx", e.getMessage());} catch (NoSuchAlgorithmException e) {Log.e("xx", e.getMessage());} catch (CertificateException e) {Log.e("xx", e.getMessage());} catch (IOException e) {Log.e("xx", e.getMessage());} catch (KeyStoreException e) {Log.e("xx", e.getMessage());} catch (KeyManagementException e) {Log.e("xx", e.getMessage());}}private static class SavingTrustManager implements X509TrustManager {private final X509TrustManager tm;private X509Certificate[] chain;SavingTrustManager(X509TrustManager tm) {this.tm = tm;}public X509Certificate[] getAcceptedIssuers() {throw new UnsupportedOperationException();}public void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {throw new UnsupportedOperationException();}public void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {this.chain = chain;tm.checkServerTrusted(chain, authType);}}}
更多相关文章
- android https之三
- Android(安卓)中从res/values/strings.xml中读取具体的字符串的
- Android(安卓)中从res/values/strings.xml中读取具体的字符串的
- 更改TextView的背景色
- 更改手机窗口画面底色
- android 读取通讯录显示到gridview
- 更改TextView的字体颜色
- Android(安卓)Contacts(一)—— 读取联系人
- android https之二