欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java开发https请求ssl不受信任问题解决方法

程序员文章站 2023-12-05 16:20:40
本文主要讨论的是java开发https请求ssl不受信任的解决方法,具体分析及实现代码如下。 在java代码中请求https链接的时候,可能会报下面这个错误 jav...

本文主要讨论的是java开发https请求ssl不受信任的解决方法,具体分析及实现代码如下。

在java代码中请求https链接的时候,可能会报下面这个错误

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

原因是没有证书。在浏览器中直接使用url访问是可以的,应该是浏览器之前就保存过对应的.cer证书。

解决方法有两种,从目标机器获得有效证书或者忽略证书信任问题。

一、获得目标机器有效证书

1、编译安装证书程序 javac installcert.java(代码如下)

/* 
 * copyright 2006 sun microsystems, inc. all rights reserved. 
 * 
 * redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions 
 * are met: 
 * 
 *  - redistributions of source code must retain the above copyright 
 *   notice, this list of conditions and the following disclaimer. 
 * 
 *  - redistributions in binary form must reproduce the above copyright 
 *   notice, this list of conditions and the following disclaimer in the 
 *   documentation and/or other materials provided with the distribution. 
 * 
 *  - neither the name of sun microsystems nor the names of its 
 *   contributors may be used to endorse or promote products derived 
 *   from this software without specific prior written permission. 
 * 
 * this software is provided by the copyright holders and contributors "as 
 * is" and any express or implied warranties, including, but not limited to, 
 * the implied warranties of merchantability and fitness for a particular 
 * purpose are disclaimed. in no event shall the copyright owner or 
 * contributors be liable for any direct, indirect, incidental, special, 
 * exemplary, or consequential damages (including, but not limited to, 
 * procurement of substitute goods or services; loss of use, data, or 
 * profits; or business interruption) however caused and on any theory of 
 * liability, whether in contract, strict liability, or tort (including 
 * negligence or otherwise) arising in any way out of the use of this 
 * software, even if advised of the possibility of such damage. 
 */
/** 
 * http://blogs.sun.com/andreas/resource/installcert.java 
 * use: 
 * java installcert hostname 
 * example: 
 *% java installcert ecc.fedora.redhat.com 
 */
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;
/** 
 * class used to add the server's certificate to the keystore 
 * with your trusted certificates. 
 */
public class installcert {
	public static void main(string[] args) throws exception {
		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]);
			string p = (args.length == 1) ? "changeit" : args[1];
			passphrase = p.tochararray();
		} else {
			system.out.println("usage: java installcert <host>[:port] [passphrase]");
			return;
		}
		file file = new file("jssecacerts");
		if (file.isfile() == false) {
			char sep = file.separatorchar;
			file dir = new file(system.getproperty("java.home") + sep 
			          + "lib" + sep + "security");
			file = new file(dir, "jssecacerts");
			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;
		}
		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);
		}
	}
}

2、运行安装证书程序生成证书

java installcert my.hoolai.com

例如:java instalcert smtp.zhangsan.com:465 admin
如果不加参数password和host的端口号,上面的获取证书程序中默认给的端口号是:443,密码是:changeit

3、根据运行提示信息,输入1,回车,在当前目录下生成名为: jssecacerts 的证书

将证书放置到$java_home/jre/lib/security目录下, 切记该jdk的jre是工程所用的环境!!!

或者:

system.setproperty("javax.net.ssl.truststore", "你的jssecacerts证书路径");

可以更改密码,在security目录下运行命令

keytool -storepasswd -new xxxcom -keystore cacerts

就可以修改密码,修改后使用命令

keytool -list -v -keystore cacerts

查看文件的信息,会提示需要密码才能查看,如果输入密码与修改后的密码匹配,说明修改成功了。

ps:至此这种方式可以成功使用ssl了,另外再补充一下,根据刚才生成的文件jssecacerts,可以生成cer文件,

命令如下

keytool -export -alias xxx.com-1 -keystore jssecacerts -rfc -file xxx.cer

如上,之前的工具类中默认命名别名是加上"-1"。使用installcert设置的密码需要跟cacerts文件中的密码一致,

如果修改过密码,就需要修改installcert类中对应的密码字符串,否则会有下面这个异常:

java.security.unrecoverablekeyexception: password verification failed

二、忽略证书信任问题

源码:http://mengyang.iteye.com/blog/575671

一定要注意需要在connection创建之前调用文章里所述的方法,像这个样子:

trustallhttpscertificates();
hostnameverifier hv = new hostnameverifier() { 
    public boolean verify(string urlhostname, sslsession session) { 
      return true; 
    } 
  };
httpsurlconnection.setdefaulthostnameverifier(hv);
connection = (httpurlconnection) url.openconnection();

好吧,两种方法都试过有效。

总结

以上就是本文关于java开发https请求ssl不受信任问题解决方法的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!