可能重复:
Generate certificates, public and private keys with 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完成上述所有操作。
我可以使用哪些库?
答案 0 :(得分:27)
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);
}
}
答案 1 :(得分:4)
使用BouncyCastle生成证书。我相信它还允许您将它们导入Java密钥库。
此外,您的问题似乎与this one非常相似。