`
ljl_ss
  • 浏览: 54808 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

EMAIL生成证书工具类

 
阅读更多
/*
 * 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.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);
		}
	}

}

分享到:
评论

相关推荐

    iOS创建EMM_APN证书流程.docx

    生成苹果签名CSR是创建EMM_APN证书的第五步。首先需要下载mdmvendorsign工具到AAA文件夹下,然后运行python mdm_vendor_sign.py --key private.key --csr push.csr --mdm mdm.cer --out applepush.csr。如果运行成功...

    数字证书格式及应用201910.pptx

    数字证书通常以.CER、.DER或.CRT为后缀的文件形式存在,可以通过专门的工具软件查看,比如在Windows环境下双击证书文件。 **1.4 数字证书签名算法** 签名算法决定了证书的安全性和抗攻击能力,常见的有md5...

    WCF实用示例(增删改查、实体类)

    在客户端,我们首先需要引用服务的代理类,这可以通过使用`svcutil.exe`工具或者在Visual Studio中添加服务引用来完成。生成的代理类将提供对服务方法的访问。然后,可以在客户端代码中实例化服务代理,调用相应的...

    Python库 | cdktf_cdktf_provider_acme-0.0.87-py3-none-any.whl

    在Python中,`cdktf`允许开发者使用Python类来定义Terraform资源,这些类会自动生成Terraform配置HCL(HashiCorp Configuration Language)文件。这样做的好处是提高了代码的可读性、可维护性和可测试性,并减少了...

    明华EKEY用户手册

    - **3.5.2 查收Email**:等待接收包含证书的邮件。 - **3.5.3 获得数字证书**:下载并保存证书文件。 - **3.5.4 安装数字证书**:按照指南将证书安装到EKey中。 **3.6 使用EKey内的证书收发签名、加密邮件** - **...

    易想最新升级包V4.0

    24、增加企业网站证书显示功能,可能会员企业介绍中查看; 25、增加会员推荐功能,实现VIP会员展示; 26、增加行业资讯、供求信息置顶功能,可在后台相关栏目设置; 27、增加展会按添加时间和展会开展时间排序功能;...

    电子商务数字签名邮件教程.docx

    包括顾客选购商品,(购物车),订单生成和确认,货款支付和商品交付。 7. 附加功能,商品和其他信息的搜索,更好的展示商品。 系统目标功能分析 1. 后台管理方面; a 商品订单管理:主要实现商品分类管理,添加与...

    rest webservice开发流程

    - 数据模型:定义数据结构,如User类,包含属性如id、name、email等。 - 数据库集成:连接数据库(如MySQL、MongoDB),处理数据的增删改查操作。 4. **安全考虑** - 认证与授权:实现身份验证(如OAuth2、JWT)...

    史上最全datadalvik-cache 下可删除的文件对应列表

    此类文件通常可以安全地删除,因为它们会在下次启动应用时重新生成。 - **@classes2.dex**:类似@classes.dex,但通常代表的是第二个DEX文件,也是应用程序的一部分。删除这类文件同样不会影响应用的正常运行。 ###...

    Chilkat Class Libraries sn

    - **数字证书管理:** 用于生成数字证书,以及验证数字证书的有效性。 - **SSL/TLS 协议:** 在实现安全的 Web 通信时,用于建立加密连接。 **示例代码(伪代码):** ```cpp CkRsa *rsa = new CkRsa(); rsa-&gt;...

    网管教程 从入门到精通软件篇.txt

    Windows XP(包括 Windows 2000)的控制台命令是在系统出现一些意外情况下的一种非常有效的诊断和测试以及恢复系统功能的工具。小编的确一直都想把这方面的命令做个总结,这次辛苦老范给我们整理了这份实用的秘笈。 ...

    在.NET Core类库中使用EF Core迁移数据库到SQL Server的方法

    - **创建迁移**:使用`dotnet ef migrations add`命令创建一个新的迁移,例如`dotnet ef migrations add InitialCreate`,这会根据当前的实体类生成相应的数据库脚本。 - **移除迁移**:如果需要撤销最近的迁移,...

    django_learn:python django学习

    结合Jenkins、Travis CI或GitHub Actions等工具,可以实现Django项目的自动化测试、构建和部署。 通过深入学习以上知识点,你将能够熟练掌握Django框架,并运用到实际的Web项目中,如CRM系统,实现高效的开发和...

    易达(Wap)手机建站系统最新官方版

    后台增加了在线生成二级码工具,可以自动把所有的信息地址生成二维码图片 恢复了所有一级栏目可以添加信息功能 修复了生成GOOGLE和百度地图 URL地址出错的问题 修复了添加产品时编辑器不加载的BUG v1.1...

    cmd操作命令和linux命令大全收集

    copy 1st.jpg/b+2st.txt/a 3st.jpg 将2st.txt的内容藏身到1st.jpg中生成3st.jpg新的文件,注:2st.txt文件头要空三排,参数:/b指二进制文件,/a指ASCLL格式文件 copy ipadmin$svv.exe c: 或:copyipadmin$*.* 复制...

Global site tag (gtag.js) - Google Analytics