Tomcat应用访问SSL或https失败的解决办法
一,首先,解决unable to find valid certification path to requested target的问题。
其实就是要生成证书, 让tomcat读取证书
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager; 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);
}
} }
在把证书放到$JAVA_HOME/jre/lib/security目录下
要么就是在浏览器里面打开网站的证书, 导出来上传到服务器上, 然后导入到tomcat默认的cacerts
二,然后, 如果问题未解决出现“Certificate doesn't match any of the subject alternative names”
这时候, 需要改造代码
a. 方案1:使用HttpURLConnection 请求https地址, 例子如下:
import java.net.HttpURLConnection; public static HttpURLConnection connectToWeb(String uri) {
HttpURLConnection connection = null;
try {
URL url = new URL(uri);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return connection;
}
b.方案2:使用SSLConnectionSocketFactory,例子如下:
public static CloseableHttpClient createSSLClientDefault() {
CloseableHttpClient client = null;
try {
SSLContext sslContext = null;
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);//这里的红色部分
client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
e.printStackTrace();
}
return client;
}
Tomcat应用访问SSL或https失败的解决办法的更多相关文章
- 数据库无法访问,用户 NT AUTHORITY/SYSTEM或NT AUTHORITY\NETWORK SERVICE登录失败的解决办法
问题:win7中的在IIS 7.0中,在 Default Web Site 目录下挂一虚拟目录. 在相应的应用程序池 DefaultAppPool 设置标识设置成NetworkService. 但是打 ...
- tomcat启动失败的解决办法
初次安装tomcat启动失败的解决办法: 1.CATALINA_HOME C:\Program Files\apache-tomcat-8.5.242.path %CATALINA_HOME% ...
- Windows开启关闭测试模式的方法(含开启测试模式失败的解决办法)
前言: 内含:Windows开启关闭测试模式的方法.开启测试模式失败的解决办法.win10进入bios的方式.BitLocker恢复方式. 对于互联网从业者来说 ...
- LoadLibrary加载动态库失败的解决办法
from:http://blog.sina.com.cn/s/blog_62ad1b8101017qub.html 若DLL不在调用方的同一目录下,可以用LoadLibrary(L"DLL绝 ...
- Data Base sqlServer sa用户登陆失败的解决办法
sqlserver sa用户登陆失败的解决办法 如下图以此模仿: 1.右键-属性 2.找到安全: 3.勾选如图: 4.sa用户密码重置: 5.服务重启:
- 微信公众平台Token验证失败的解决办法
微信公众平台Token验证失败的解决办法 1.可查看url和token是否正确 2.查看服务器端口是否为80端口 3.你可以通过记录log日志来判断是否接受到微信提交过来的信息 1.$fp=fopen ...
- Sql Server 2008 卸载重新安装失败的解决办法!(多次偿试,方法均有效!)
Sql Server 2008 卸载重新安装失败的解决办法!(多次偿试,方法均有效!) 1.控制面板中卸载所有带sql server的程序. 2.在C盘C:\Program Files中sqlserv ...
- npm install 错误 安装 chromedriver 失败的解决办法
npm 安装 chromedriver 失败的解决办法npm 安装 chromedriver 时,偶尔会出错,错误提示类似于:npm ERR! chromedriver@2.35.0 install: ...
- WCF传输过大的数据导致失败的解决办法
WCF传输过大的数据导致失败的解决办法 WCF服务默认是不配置数据传输的限制大小的,那么默认的大小好像是65535B,这才65KB左右,如果希望传输更大一些的数据呢,就需要手动指定一下缓冲区的大小 ...
随机推荐
- Qt编写自定义控件37-发光按钮(会呼吸的痛)
一.前言 这个控件是好早以前写的,已经授权过好几个人开源过此控件代码,比如红磨坊小胖,此控件并不是来源于真实需求,而仅仅是突发奇想,类似于星星的闪烁,越到边缘越来越淡,定时器动态改变边缘发光的亮度,产 ...
- IDEA中提示Error:java: Compilation failed: internal java compiler error
解决办法:File-->Setting...-->Build,Execution,Deployment-->Compiler-->Java Compiler 设置相应Modul ...
- Delphi下Treeview控件基于节点编号的访问1
有时我们需要保存和重建treeview控件,本文提供一种方法,通过以树结构节点的编号访问树结构,该控件主要提供的方法如下: function GetGlobeNumCode(inNode:T ...
- 第三方框架MBProgressHUD-----实现各种提示框
程序运行显示如下 : 点击按钮实现对应的提示框: 这里只截取了其中一张图,有兴趣的可以自己运行程序,查看其他的几种提示框哟!!! 第三方框架MBProgressHUD的下载地址:https://git ...
- godot新手教程1[button信号使用]<godot节点信号对照及节点属性用法>
button(按钮)节点信号对照: 1:pressed() #按钮点击信号 #绑定按钮点击后触发信号 Pressed使用案例: func _on_”节点路径”_Button_pressed( ...
- 【ARM-Linux开发】Linux查看设备驱动
驱动操作命令: insmod / modprobe 加载驱动 rmmod 卸载驱动 lsmod 查看系统中所有已经被 ...
- js删除array数组中元素
for(var i = 0; i < array.length; i++) { if(-1 != array[i]) { array.splice(i, 1); i--; } } 上面if就是判 ...
- IntelliJ IDEA 简单设置
1.在idea中添加try/catch的快捷键 ctrl+alt+t 2.主题修改 选择菜单栏“File--settings--apperance--theme”,主题选择Darcula: 3.代码字 ...
- Word 分栏页码,一个页面两个不同页码的设置
1. 前言 在一些报纸.杂志中,我们可以见到各种各样的排版风格效果,其中有一种效果是一个页面设置了两栏,并且每栏下面都有不同的页码,那么,这种效果是如何实现的呢?这种页码在Word中默认页码样式中是没 ...
- Idea生成的的第一个eureka注册中心服务器
操作: 1.file->new->project Spring Initializer ->default 点击next 2.输入 Group ...