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

2023-11-26

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

JAVA 代码可以在任何地方执行此操作吗?

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

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

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

非常感谢


以下代码插入CA证书文件yourcert.cer进入你的密钥库而不使用keytool:

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;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

以编程方式将 CA 信任证书导入现有密钥库文件,而不使用 keytool 的相关文章

随机推荐