我编写了以下代码,使用客户端证书身份验证连接到服务器。
public void login()
{
try {
KeyStore ks = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
ks.load(null, null);
String kalg = KeyManagerFactory.getDefaultAlgorithm();
System.out.println(kalg);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(kalg);
kmf.init(ks, null);
String talg = TrustManagerFactory.getDefaultAlgorithm();
System.out.println(talg);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(talg);
KeyStore ts;
ts = KeyStore.getInstance("Windows-ROOT", "SunMSCAPI");
ts.load(null, null);
tmf.init(ts);
TrustManager tm[] = tmf.getTrustManagers();
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(kmf.getKeyManagers(), tm, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
URL url = new URL("https://xxxxxx/");
HttpsURLConnection httpsCon = (HttpsURLConnection) url
.openConnection();
InputStream is = httpsCon.getInputStream();
httpsCon.getHeaderFields();
String str =httpsCon.getHeaderField("Set-Cookie");
System.out.println(httpsCon.getResponseMessage());
int c;
StringBuffer sb = new StringBuffer();
while ((c = is.read()) >= 0) {
System.out.print((char)c);
sb.append((char) c);
}
is.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
用于测试目的我创建了自签名服务器和客户端证书。
此代码仅适用于java 7,在java 8中它抛出异常:
java.security.InvalidKeyException:没有安装的提供程序支持 这个键:sun.security.mscapi.RSAPrivateKey
是否与java 8中引入的一些功能有关?
答案 0 :(得分:0)
public static void login()
{
try {
KeyStore ks = KeyStore.getInstance("Windows-MY");
ks.load(null, null);
String kalg = KeyManagerFactory.getDefaultAlgorithm();
System.out.println(kalg);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(kalg);
kmf.init(ks, null);
String talg = TrustManagerFactory.getDefaultAlgorithm();
System.out.println(talg);
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(final X509Certificate[] chain,
final String authType) {
}
@Override
public void checkServerTrusted(final X509Certificate[] chain,
final String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
} };
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(kmf.getKeyManagers(), trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
URL url = new URL("xxxxx");
HttpsURLConnection httpsCon = (HttpsURLConnection) url
.openConnection();
InputStream is = httpsCon.getInputStream();
httpsCon.getHeaderFields();
String str =httpsCon.getHeaderField("Set-Cookie");
System.out.println(httpsCon.getResponseMessage());
int c;
StringBuffer sb = new StringBuffer();
while ((c = is.read()) >= 0) {
System.out.print((char)c);
sb.append((char) c);
}
is.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}