gpt4 book ai didi

java - 以编程方式将 CA 信任证书导入现有的 keystore 文件,而不使用 keytool

转载 作者:IT老高 更新时间:2023-10-28 21:14:57 29 4
gpt4 key购买 nike

我想创建一个 JAVA 程序,将 .cer CA 导入现有的 keystore 文件。这样最终用户可以更方便地插入 CA 证书(无需在命令中使用 CMD 和 key)。

JAVA 代码可以做到这一点吗?

我尝试了一些方法,但仍然无法将证书导入 java

CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream certstream = fullStream (certfile);
Certificate certs = cf.generateCertificates(certstream);

错误是不兼容的类型,还有其他建议吗?

非常感谢

最佳答案

以下代码在不使用 keytool 的情况下将 CA 证书文件 yourcert.cer 插入到您的 keystore 中:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.io.IOException;
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.ByteArrayInputStream;
import java.security.spec.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Collection;

public class ImportCA {

public static void main(String[] argv) throws Exception {
String certfile = "yourcert.cer"; /*your cert path*/
FileInputStream is = new FileInputStream("yourKeyStore.keystore");

KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(is, "yourKeyStorePass".toCharArray());

String alias = "youralias";
char[] password = "yourKeyStorePass".toCharArray();

//////

CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream certstream = fullStream (certfile);
Certificate certs = cf.generateCertificate(certstream);

///
File keystoreFile = new File("yourKeyStorePass.keystore");
// Load the keystore contents
FileInputStream in = new FileInputStream(keystoreFile);
keystore.load(in, password);
in.close();

// Add the certificate
keystore.setCertificateEntry(alias, certs);

// Save the new keystore contents
FileOutputStream out = new FileOutputStream(keystoreFile);
keystore.store(out, password);
out.close();
}

private static InputStream fullStream ( String fname ) throws IOException {
FileInputStream fis = new FileInputStream(fname);
DataInputStream dis = new DataInputStream(fis);
byte[] bytes = new byte[dis.available()];
dis.readFully(bytes);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
return bais;
}
}

关于java - 以编程方式将 CA 信任证书导入现有的 keystore 文件,而不使用 keytool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18889058/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com