这是我现在用来生成数字证书的代码。现在,我能够生成一个带有私钥密码保护的数字证书。
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
testKeyStore();
}
public static void testKeyStore() throws Exception {
try {
String storeName = "d://suresh_test.cer";
java.security.KeyPairGenerator keyPairGenerator = KeyPairGenerator
.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
X509Certificate trustCert = createCertificate("CN=CA", "CN=CA",
publicKey, privateKey);
java.security.cert.Certificate[] outChain = {
createCertificate("CN=Client", "CN=CA", publicKey,
privateKey), trustCert };
KeyStore outStore = KeyStore.getInstance("PKCS12");
outStore.load(null, "suresh_".toCharArray());
outStore.setKeyEntry("mykey", privateKey, "suresh_".toCharArray(),
outChain);
OutputStream outputStream = new FileOutputStream(storeName);
outStore.store(outputStream, "suresh_".toCharArray());
outputStream.flush();
outputStream.close();
KeyStore inStore = KeyStore.getInstance("PKCS12");
inStore.load(new FileInputStream(storeName),
"suresh_".toCharArray());
} catch (Exception e) {
e.printStackTrace();
throw new AssertionError(e.getMessage());
}
}
private static X509Certificate createCertificate(String dn, String issuer,
PublicKey publicKey, PrivateKey privateKey) throws Exception {
X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
certGenerator.setSerialNumber(BigInteger.valueOf(Math.abs(new Random()
.nextLong())));
certGenerator.setIssuerDN(new X509Name(dn));
certGenerator.setSubjectDN(new X509Name(dn));
certGenerator.setIssuerDN(new X509Name(issuer)); // Set issuer!
certGenerator.setNotBefore(Calendar.getInstance().getTime());
certGenerator.setNotAfter(Calendar.getInstance().getTime());
certGenerator.setPublicKey(publicKey);
certGenerator.setSignatureAlgorithm("SHA1WithRSAEncryption");
X509Certificate certificate = (X509Certificate) certGenerator.generate(
privateKey, "BC");
return certificate;
}
如何自签名?
我一点头绪都没有。
我该怎么进行呢?
谢谢任何提示。