以编程方式将自签名证书添加到密钥库/信任库 [英] Programmatically add a self-signed certificate to your keystore/truststore

查看:272
本文介绍了以编程方式将自签名证书添加到密钥库/信任库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到这个问题(以及其他)解释了如何使用命令行手动将(自签名)证书添加到密钥库/ cacerts。执行此操作时,如果您获得了证书(.cert文件),则可以与没有签名证书的服务器建立安全连接。这对于测试目的非常有用。

I saw this question (and others) where it is explained how to add a (self-signed) certificate to your keystore/cacerts manually by using the commandline. When doing this, you can set up a secured connection with a server without a signed certificate, if you were given the certificate (.cert file). This is can be useful for testing purposes.

我想对此进行编程,因此用户无需手动执行此操作。基本概念如下:用户拥有.cert文件的本地副本,并为我的程序提供该文件驻留在其文件系统中的路径。我的程序获取文件并将其添加到密钥库。

I would like to program this, so users don't need to do this manually. The basic concept would be the following: The user has a local copy of the .cert file, and gives my program the path to where that file resides in his file system. My program fetches the file and adds it to the keystore.

我的问题是:如何将此证书添加到我的程序中的密钥库中,以便turstmanager接受它作为一个值得信赖/签名的证书,给定.cert文件的(路径)?是否有关于此问题的任何教程或代码片段?

My question is: how to add this certificate to the keystore within my program, so that the turstmanager will accept it as a trustworthy/signed certificate, given the (path) to the .cert file? Are there any tutorials or code snippets regarding to this problem?

PS:我不需要接受所有证书的trustmanager技巧,如上所述其他

PS: I do NOT need the "accept all certificates" trustmanager trick as described here

推荐答案

相当简单:

InputStream input = ...;
CertificateFactory factory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) factory.generateCertificate(input);
KeyStore keystore = ...;
keystore.setCertificateEntry(alias, cert);

从javadoc中可以看出加载和存储密钥库: http://docs.oracle.com/javase/6/docs/api/java/security/KeyStore .html

Loading and storing the keystore is evident from the javadoc: http://docs.oracle.com/javase/6/docs/api/java/security/KeyStore.html

这篇关于以编程方式将自签名证书添加到密钥库/信任库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆