以编程方式将 CA 信任证书导入现有密钥库文件,而无需使用 keytool

2022-09-01 03:45:26

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

这是JAVA代码可以做到这一点的地方吗?

我尝试了某种方式,但仍然无法将证书放入java

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

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

谢谢很多


答案 1

以下代码将 CA 证书文件插入到密钥库中,而无需使用:yourcert.cerkeytool

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;
    }
}

答案 2

从链接下载证书并存储到特定路径中。然后在运行时使用以下代码将该文件加载到 trustStore 中。我希望这个exaple会帮助你..

KeyStore keyStore = KeyStore.getInstance("JKS");
String fileName = "D:\\certs_path\\cacerts"; // cerrtification file path
System.setProperty("javax.net.ssl.trustStore", fileName);

推荐