在 Java 中创建密钥库文件 (.jks) 和自签名证书 (.cer/.crt)

Create a keystore file (.jks) and a self signed certificate (.cer/.crt) in Java

我想在 Java 中创建一个密钥库文件 (.jks) 和一个自签名证书 (.cer/.crt)。我正在尝试这个:

生成密钥库:

protected void getKeyStore(X509Certificate certificate)
{
    File newSnKeyStoreFile = new File("Mypath..\keyStore.jks");

    try {

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);

        if(!certificate.toString().isEmpty())
        {
            keyStore.store(new FileOutputStream(newSnKeyStoreFile), "password".toCharArray());
            if (keyStore.getCertificateAlias(certificate) == null) {
                keyStore.setCertificateEntry("cert"+ count++, certificate);
            }
        }
        keyStore.store(new FileOutputStream(newSnKeyStoreFile), KEYSTORE_PASSWORD.toCharArray());

        // Write to .jks file
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new FileWriter(newSnKeyStoreFile));
            out.write(keyStore.toString());
        } catch ( Exception e ) {
            e.printStackTrace();
        } finally {
            if ( out != null ) out.close();
        }
    }catch(Exception ke){
        System.out.print("Error occurred while setting up keyStore: " + ke.getMessage());
    }
}

我生成证书:

protected X509Certificate genCertificate()
{
    try {
        //Generate self signed certificate
        CertAndKeyGen gen = new CertAndKeyGen("RSA", "SHA1WithRSA")
        gen.generate(1024);
        X509Certificate cert = gen.getSelfCertificate(new X500Name("CN=ROOT"), (long) 365 * 24 * 3600);

        File certFile = new File("Mypath..\Cert.cer");
        // Write to .cer file
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new FileWriter(certFile));
            out.write(certificate.getEncoded().toString());
        } catch ( Exception e ) {
            e.printStackTrace();
        } finally {
            if ( out != null ) out.close();
        }
        return cert;

    }catch (Exception e) {
        System.out.println("Error : " + e.getMessage());
    }
    return null;
}

现在,当我 运行 这样做时,会创建 .jks 和 .cer 文件,但是当我尝试使用 cmd 命令检查密钥库时,出现错误:

命令 - keytool -list -keystore keyStore.jks

keytool error: java.io.IOException: Invalid keystore format

命令 - keytool -printcert -v -file Cert.cer

keytool error: java.lang.Exception: Empty input
java.lang.Exception: Empty input
        at sun.security.tools.KeyTool.printCertFromStream(KeyTool.java:2234)
        at sun.security.tools.KeyTool.doPrintCert(KeyTool.java:2423)
        at sun.security.tools.KeyTool.doCommands(KeyTool.java:1069)
        at sun.security.tools.KeyTool.run(KeyTool.java:340)
        at sun.security.tools.KeyTool.main(KeyTool.java:333)

关于我可能哪里出错的任何指示?

protected void getKeyStore(X509Certificate certificate)
{
    File newSnKeyStoreFile = new File("Mypath..\keyStore.jks");

    try {

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);

        if(!certificate.toString().isEmpty())

这个测试毫无意义。如果您有证书,则其字符串表示形式不会为空。如果不这样做,则根本不应该调用此方法。移除。

        {
            keyStore.store(new FileOutputStream(newSnKeyStoreFile), "password".toCharArray());

为什么?里面什么都没有。移除。

            if (keyStore.getCertificateAlias(certificate) == null) {
                keyStore.setCertificateEntry("cert"+ count++, certificate);

如果它不为空,您应该覆盖该条目或抛出异常,而不是静静地忽略该条件。

            }
        }
        keyStore.store(new FileOutputStream(newSnKeyStoreFile), KEYSTORE_PASSWORD.toCharArray());

很好,但你需要关闭此 FileOutputStream

        // Write to .jks file
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new FileWriter(newSnKeyStoreFile));
            out.write(keyStore.toString());
        } catch ( Exception e ) {
            e.printStackTrace();
        } finally {
            if ( out != null ) out.close();
        }

删除所有这些毫无意义的垃圾。您已经存储了密钥库。你在这里所做的一切都是在破坏它。

   File certFile = new File("Mypath..\Cert.cer");
    // Write to .cer file
    BufferedWriter out = null;

错了。证书文件是二进制的。使用 FileOutputStream.

    try {
        out = new BufferedWriter(new FileWriter(certFile));

错了,见上文。 out = new FileOutputStream(certFile);

        out.write(certificate.getEncoded().toString());

又错了。这应该是

out.write(certificate.getEncoded());

您似乎对将事物转换为字符串有一种狂热。尝试逐渐减少。