Java 以编程方式将自签名证书添加到您的密钥库/信任库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21775408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:35:36  来源:igfitidea点击:

Programmatically add a self-signed certificate to your keystore/truststore

javasslkeystore

提问by user1884155

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.

我看到了这个问题(和其他问题),其中解释了如何使用命令行手动将(自签名)证书添加到您的密钥库/cacerts。执行此操作时,如果您获得了证书(.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.

我想对此进行编程,因此用户无需手动执行此操作。基本概念如下:用户拥有 .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?

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

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

PS:我不需要这里描述的“接受所有证书”信任管理器技巧

采纳答案by nablex

Rather simple:

相当简单:

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

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

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