12

可能重复:
使用 Java 生成证书、公钥和私钥

我需要在运行时生成自签名证书,对其进行签名并导入到 Java 密钥库。我可以通过以下方式在命令行中使用“keytool”和“openssl”来做到这一点:

keytool -import -alias root -keystore keystore.txt -file cacert.pem
keytool -genkey -keyalg RSA -keysize 1024 -alias www.cia.gov -keystore keystore.txt
keytool -keystore keystore.txt -certreq -alias www.cia.gov -file req.pem
openssl x509 -req -days 3650 -in req.pem -CA cacert.pem -CAkey cakey.pem -CAcreateserial -out reqsigned.pem 
keytool -import -alias www.cia.gov -keystore keystore.txt -trustcacerts  -file reqsigned.pem

当然,我可以使用 keytool 和 openssl 二进制文件发布我的应用程序,并从 Java 执行上述命令,但我正在寻找一种更简洁的方法,它允许我使用纯 Java 完成上述所有操作。

我可以使用任何库吗?

4

2 回答 2

30
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Date;

// import sun.security.tools.keytool.CertAndKeyGen; // Use this for Java 8 and above
import sun.security.x509.CertAndKeyGen;
import sun.security.x509.X500Name;

public class UseKeyTool {

    private static final int keysize = 1024;
    private static final String commonName = "www.test.de";
    private static final String organizationalUnit = "IT";
    private static final String organization = "test";
    private static final String city = "test";
    private static final String state = "test";
    private static final String country = "DE";
    private static final long validity = 1096; // 3 years
    private static final String alias = "tomcat";
    private static final char[] keyPass = "changeit".toCharArray();

    // copied most ideas from sun.security.tools.KeyTool.java

    @SuppressWarnings("restriction")
    public static void main(String[] args) throws Exception {

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

        CertAndKeyGen keypair = new CertAndKeyGen("RSA", "SHA1WithRSA", null);

        X500Name x500Name = new X500Name(commonName, organizationalUnit, organization, city, state, country);

        keypair.generate(keysize);
        PrivateKey privKey = keypair.getPrivateKey();

        X509Certificate[] chain = new X509Certificate[1];

        chain[0] = keypair.getSelfCertificate(x500Name, new Date(), (long) validity * 24 * 60 * 60);

        keyStore.setKeyEntry(alias, privKey, keyPass, chain);

        keyStore.store(new FileOutputStream(".keystore"), keyPass);



    }
}
于 2011-09-05T06:46:33.550 回答
5

使用BouncyCastle生成证书。我相信它还允许您将它们导入 Java 密钥库。

此外,您的问题似乎与问题非常相似。

于 2011-01-08T13:44:02.160 回答