Java手动添加SSL证书

出现错误为 SSLHandshakeException - unable to find valid certification path to requested target

在服务器上找到对应的jssecacerts文件或cacerts, 一般在 <jre home>/lib/security 目录下, 在本地执行以下代码, 将cert添加到文件里,

再用新产生的jssecacerts放回覆盖旧文件(建议先备份)

package com.rockbb.test;

/*
 * 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.
 */

import java.io.*;
import java.net.URL;

import java.security.*;
import java.security.cert.*;

import javax.net.ssl.*;

public class InstallCert
{

	public static void main(String[] args) throws Exception
	{
		args = new String[]{"api.weixin.qq.com"};
		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("E:\\temp\\");
			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);
		}
	}

}
时间: 2024-10-12 23:03:12

Java手动添加SSL证书的相关文章

CentOS6.5 下在Nginx中添加SSL证书以支持HTTPS协议访问

参考文献: 1. NginxV1.8.0安装与配置 2. CentOS下在Nginx中添加SSL证书以支持HTTPS协议访问 3. nginx配置ssl证书的方法 4.nginx强制使用https访问(http跳转到https) 5.nginx ssl 107 (net::ERR_SSL_PROTOCOL_ERROR) 无法与服务器建立安全连接 解决方法 配置过程如下: 我的nginx是 yum 安装 具体安装过程参考:[转]CENTOS 6.5 配置YUM安装NGINX+服务器负载均衡 一.安

LAMP环境添加SSL证书,使网站变成HTTPS加密传输

一 简介 目前国内大部分网站都是采用的HTTP协议,也就是明文传输数据,与此同时SSL证书最近几年逐渐开始在国外普及.安装SSL证书之后数据就可以进行加密传输,在浏览器中看到的效果就是:在地址栏前面带有一个绿色小锁,同时URL地址是以HTTPS开头的 下面我将简单介绍如果在LAMP环境(Linux+Apache+MySQL+PHP)下添加SSL证书的详细步骤: 二 获取证书 付费的证书有很多,这里就不说了.关于免费证书据我了解的就有:沃通免费SSL证书以及StartSSL免费SSL证书.如果想要

如何给网站添加SSL证书(免费)

上篇讲了如何将网站部署到服务器上,这篇就讲如何给网站添加SSL证书. 1.先到腾讯云ssl证书认证那里申请一个证书 2.DNS认证 3.下载解压nginx里面的文件 4. 在服务器上/www目录下创建文件夹ssl,将解压的文件上传到ssl 5.进入cd /etc/nginx/conf.d/下面修改网站的.conf后缀名文件 6.检查文件是否成功和重启 7.认证成功 结语:过程总是遇到很多问题,不过一步步来还是能够解决的. Node+mongodb线上部署到阿里云 原文地址:https://www

添加ssl证书

ssl证书会使你的网站更加安全,防止isp在你的网站显示时添加广告,浏览网页时地址栏左边有一个绿色安全的图标,使用户感觉更加安全放心. 颁发ssl证书的机构很多,有收费的,也有免费的.当然对于自己的小网站来说,免费的足够了.我选择了letsencrypt,他可以免费给我们颁发ssl证书,操作简单便捷,唯一的缺点就是ssl证书没三个月后需要手动续期,当然你可以写程序或者用网上的工具自动续期,这对于我们程序员来说这都不是事. 下边说步骤: 1.首先打开官网 https://letsencrypt.o

Java程序避开SSL证书问题访问https网站

部分原创,参考:参考:http://tanyongbing.iteye.com/blog/1855132 在项目开发中,有时会遇到与SSL安全证书导入打交道的,如何把证书导入java中的cacerts证书库呢? 其实很简单,方法如下: 每一步:使用Firefox浏览器,进入某个https://www.xxx.com开头的网站,把要导入的证书下载过来, 点击浏览器导航栏左边的锁,查看安全链接的更多信息,点击查看证书,点击详细信息,点击导出,保存类型"X.509证书(PEM)(*.crt; *.pe

给php添加ssl证书

composer下载时报错: The "https://packagist.org/packages.json" file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed 解决办法: 这是因为连接packag

nginx 添加ssl证书

第一步: 获取linux的证书格式  .crt  .key 第二步: 在nginx中default.conf中再添加一个server 第三步: 内容举例如下: server { #这里开始 listen 443 ssl; server_name www.wzzbxt.com wzzbxt.com; ssl_certificate /etc/nginx/ssl/ssl.crt; #证书的路径 ssl_certificate_key /etc/nginx/ssl/ssl.key; #私钥的路径 ss

八大免费SSL证书-给你的网站免费添加Https安全加密

评论? https://www.freehao123.com/top-8-free-ssl-cert/ 文章目录 Let's Encrypt StartSSL SSL CloudFlare SSL Wosign沃通SSL 腾讯云DV SSL 免费SSL总结 SSL证书,用于加密HTTP协议,也就是HTTPS.随着淘宝.百度等网站纷纷实现全站Https加密访问,搜索引擎对于Https更加友好,加上互联网上越来越多的人重视隐私安全,站长们给网站添加SSL证书似乎成为了一种趋势. 给自己的网站添加SS

服务器安装SSL证书教程

在当下的web服务业务中,非常流行使用SSL网站证书,很多浏览器也开启了对http头的识别,从而进行提示网站数据通讯是否安全,在过去的http协议数据传输中,有非常多的不安全因素,还有可能发生域名劫持等事件,所以我们对网站开启SSL支持也是势在必行了,今天我们就以win2008为例,为大家讲解如何在win2008系统+IIS7.5中安装我们的SSL证书,过程非常简单方便. 1.首先我们要先去为域名申请SSL证书,可以申请SSL证书的地方非常多,服务商也很多,价格各有不同,我们可以根据自己的需求,