一些入门资料:
OpenSSL 与 SSL 数字证书概念贴: https://segmentfault.com/a/1190000002568019
SSL/TLS原理详解: https://segmentfault.com/a/1190000002554673
基于OpenSSL自建CA和颁发SSL证书 https://segmentfault.com/a/1190000002569859
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
或者:
Exception in thread “main” javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
原因:客户端找不到服务端的证书(无法验证服务端的安全性)。
解决方法:
忽略证书信任问题
or
从目标网站获得、或者请其提供有效证书
JSSE是一个SSL和TLS的纯Java实现,通过JSSE可以很容易地编程实现对HTTPS站点的访问。但是,如果该站点的证书未经权威机构的验证,JSSE将拒绝信任该证书从而不能访问HTTPS站点。
JSSE中,有一个信任管理器类负责决定是否信任远端的证书,这个类有如下的处理规则:
⑴ 若系统属性javax.net.sll.trustStore指定了TrustStore文件,那么信任管理器就去jre安装路径下的lib/security/目录中寻找并使用这个文件来校验证书。
⑵ 若该系统属性没有指定TrustStore文件,它就会去jre安装路径下寻找默认的TrustStore文件,这个文件的相对路径为:lib/security/jssecacerts。
⑶ 若 jssecacerts不存在,则找cacerts文件(随JDK一起发行,含有数量有限的可信任的基本证书),此时TrustStore文件就是cacerts。
Java提供了一种非常简洁的方法来访问HTTPS网页,即使用类HttpsURLConnection、URL等。这几个类为支持HTTPS对JSSE相关类做了进一步的封装,例子如下:
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
/**
* @author Evan
*/
public class Test {
public static void main(String[] args) throws Exception {
test1();
//test2();
}
private static void test2() throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException, IOException {
URL reqURL = new URL("https://mf.joobank.com/");
//创建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();
//创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
HttpsURLConnection httpsConn = (HttpsURLConnection) reqURL.openConnection();
httpsConn.setSSLSocketFactory(ssf);
//向服务端发送数据
httpsConn.setDoOutput(true);
httpsConn.setRequestMethod("POST");
OutputStreamWriter out = new OutputStreamWriter(httpsConn.getOutputStream(), "utf-8");
out.write("java");
out.flush();
out.close();
//读取响应内容
InputStreamReader in = new InputStreamReader(httpsConn.getInputStream());
int respInt = in.read();
while (respInt != -1) {
System.out.print((char) respInt);
respInt = in.read();
}
}
private static void test1() throws IOException {
URL reqURL = new URL("https://mf.joobank.com/");
HttpsURLConnection httpsConn = (HttpsURLConnection) reqURL.openConnection();
//向服务端发送数据
httpsConn.setDoOutput(true);
httpsConn.setRequestMethod("POST");
OutputStreamWriter out = new OutputStreamWriter(httpsConn.getOutputStream(), "utf-8");
out.write("java");
out.flush();
out.close();
//读取响应内容
InputStreamReader in = new InputStreamReader(httpsConn.getInputStream());
int respInt = in.read();
while (respInt != -1) {
System.out.print((char) respInt);
respInt = in.read();
}
}
}
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
//不需要对客户端进行认证,因此我们只需要执行默认的信任管理器的这个方法
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
//简单不做任何处理,即一个空的函数体,由于不会抛出异常,它就会信任任何证书。
}
@Override
public X509Certificate[] getAcceptedIssuers() {
//返回受信任的X509证书数组。
return new X509Certificate[0];
}
}
除了忽略证书校验也可以将服务端证书添加到本地JRE证书库解决报错~
###方法 2)导入证书:
导入证书方法1)通过浏览器打开目标网站,下载证书
点击安全-有效-详细信息-复制到文件,保存格式选择第一种即可
证书下载到本地后要使用jdk的keytool工具导入JRE证书库,重启java应用生效:
查看当前证书库
keytool -list -keystore D:\software\java\jdk8\jdk1.8.0_71\jre\lib\security\cacerts -storepass changeit
导入证书到当前证书库
keytool -import -trustcacerts -alias zhubang -keystore D:\software\java\jdk8\jdk1.8.0_71\jre\lib\security\cacerts -file d:\zhubang.cer -storepass changeit
指定别名查看
keytool -list -alias zhubang -keystore D:\software\java\jdk8\jdk1.8.0_71\jre\lib\security\cacerts -storepass changeit
删除指定别名的证书
keytool -delete -alias zhubang -keystore D:\software\java\jdk8\jdk1.8.0_71\jre\lib\security\cacerts -storepass changeit
导入证书方法2)通过java代码(工具类),下载证书
import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* 工具类功能描述:
* 下载指定网站的https证书保存到本地
*
* 使用方法:
* 根据运行提示信息,输入1,回车,在当前目录下生成名为:jssecacerts 的证书
* 将证书放置到$JAVA_HOME/jre/lib/security目录下重启java程序即可生效,切记该JDK的jre是当前工程所用的环境
* 或者根据刚才生成的文件jssecacerts,生成.cer文件,然后通过import导入JRE下的cacerts证书库,这样就不需要把jssecacerts放到JRE目录下
* 命令如下:
* keytool -export -alias xxx -keystore {文件路径}/jssecacerts -rfc -file yyy.cer
* 其中別名xxx要和生成jssecacerts时用的别名一致
*
* @author Evan
*/
public class InstallCacerts {
/**
* 要访问的HTTPS服务的主机名:端口,如访问 https://mf.joobank.com
*/
public static final String HOSTNAME = "mf.joobank.com";
public static void main(String[] args) throws Exception {
args = new String[]{HOSTNAME};
String host;
int port;
char[] passphrase;
if ((args.length == 1) || (args.length == 2)) {
String[] c = args[0].split(":");
host = c[0];
port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
//java keytool默认的密码是changeit
String p = (args.length == 1) ? "changeit" : args[1];
passphrase = p.toCharArray();
} else {
System.out.println("Usage: java InstallCacerts [:port] [passphrase]" );
return;
}
File file = new File("jssecacerts");
if (file.isFile() == false) {
File dir = new File(System.getProperty("java.home") + File.separatorChar + "lib" + File.separatorChar + "security");
//先看默认的证书库jssecacerts是否存在
file = new File(dir, "jssecacerts");
//如果不存在则使用cacerts(它随J2SDK一起发行,含有数量有限的可信任的基本证书)
if (file.isFile() == false) {
file = new File(dir, "cacerts");
}
}
System.out.println("Loading KeyStore " + file + "...");
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();
SSLContext context = SSLContext.getInstance("TLS");
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);
SSLSocketFactory factory = context.getSocketFactory();
System.out.println("Opening connection to " + host + ":" + port + "...");
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
socket.setSoTimeout(10000);
try {
System.out.println("Starting SSL handshake...");
socket.startHandshake();
socket.close();
System.out.println();
System.out.println("No errors, certificate is already trusted");
} catch (SSLException e) {
System.out.println();
e.printStackTrace(System.out);
}
X509Certificate[] chain = tm.chain;
if (chain == null) {
System.out.println("Could not obtain server certificate chain");
return;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println();
System.out.println("Server sent " + chain.length + " certificate(s):");
System.out.println();
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
MessageDigest md5 = MessageDigest.getInstance("MD5");
for (int i = 0; i < chain.length; i++) {
X509Certificate cert = chain[i];
System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
System.out.println(" Issuer " + cert.getIssuerDN());
sha1.update(cert.getEncoded());
System.out.println(" sha1 " + toHexString(sha1.digest()));
md5.update(cert.getEncoded());
System.out.println(" md5 " + toHexString(md5.digest()));
System.out.println();
}
System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
String line = reader.readLine().trim();
int k;
try {
k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
} catch (NumberFormatException e) {
System.out.println("KeyStore not changed");
return;
}
X509Certificate cert = chain[k];
String alias = host + "-" + (k + 1);
ks.setCertificateEntry(alias, cert);
OutputStream out = new FileOutputStream("jssecacerts");
ks.store(out, passphrase);
out.close();
System.out.println();
System.out.println(cert);
System.out.println();
System.out.println("Added certificate to keystore 'jssecacerts' using alias '" + alias + "'");
}
private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
private static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 3);
for (int b : bytes) {
b &= 0xff;
sb.append(HEXDIGITS[b >> 4]);
sb.append(HEXDIGITS[b & 15]);
sb.append(' ');
}
return sb.toString();
}
private static class SavingTrustManager implements X509TrustManager {
private final X509TrustManager tm;
private X509Certificate[] chain;
SavingTrustManager(X509TrustManager tm) {
this.tm = tm;
}
@Override
public X509Certificate[] getAcceptedIssuers() {
throw new UnsupportedOperationException();
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
throw new UnsupportedOperationException();
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
this.chain = chain;
tm.checkServerTrusted(chain, authType);
}
}
}