阅读这篇文章:

Java安全通信:HTTPS与SSL - caomiao2006的专栏 - 博客频道 - CSDN.NET  http://blog.csdn.net/caomiao2006/article/details/51762036

// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");

sslContext.init(null, tm, new java.security.SecureRandom());

// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();

URL u = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) u.openConnection();
conn.setSSLSocketFactory(ssf);

InputStream is = conn.getInputStream();


MyX509TrustManager类

import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class MyX509TrustManager implements X509TrustManager {

/*
* The default X509TrustManager returned by SunX509.  We’ll delegate
* decisions to it, and fall back to the logic in this class if the
* default X509TrustManager doesn’t trust it.
*/
X509TrustManager sunJSSEX509TrustManager;

MyX509TrustManager() throws Exception {
// create a “default” JSSE X509TrustManager.

KeyStore ks = KeyStore.getInstance("JKS");
//ks.load(new FileInputStream("trustedCerts"),
//	"passphrase".toCharArray());

TrustManagerFactory tmf =
TrustManagerFactory.getInstance("SunX509", "SunJSSE");

tmf.init(ks);

TrustManager tms [] = tmf.getTrustManagers();

/*
* Iterate over the returned trustmanagers, look
* for an instance of X509TrustManager.  If found,
* use that as our “default” trust manager.
*/
for (int i = 0; i < tms.length; i++) {
if (tms[i] instanceof X509TrustManager) {
sunJSSEX509TrustManager = (X509TrustManager) tms[i];
return;
}
}

/*
* Find some other way to initialize, or else we have to fail the
* constructor.
*/
throw new Exception("Couldn’t initialize");
}

/*
* Delegate to the default trust manager.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
sunJSSEX509TrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException excep) {
// do any special handling here, or rethrow exception.
}
}

/*
* Delegate to the default trust manager.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
sunJSSEX509TrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException excep) {
/*
* Possibly pop up a dialog box asking whether to trust the
* cert chain.
*/
}
}

/*
* Merely pass this through.
*/
public X509Certificate[] getAcceptedIssuers() {
return sunJSSEX509TrustManager.getAcceptedIssuers();
}
}


评论区

发表评论

必填

选填

选填

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

您好,欢迎到访网站!
  查看权限

«   2018年6月   »
123
45678910
11121314151617
18192021222324
252627282930

最新留言