我使用 EJBCA 从 CommonName 生成证书。在java代码中,我生成了私钥和公钥,然后生成了证书的csr。现在我以 PEM 格式 (.cer) 保存证书,但我还需要私钥,所以我想用 .pfx 或 p12 扩展名保存。我能怎么做?这是我生成证书的实际代码:
KeyPair keys;
try {
keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
//SAVE PRIVKEY
//PrivateKey privKey = keys.getPrivate();
//byte[] privateKeyBytes = privKey.getEncoded();
PKCS10CertificationRequest pkcs10 = new PKCS10CertificationRequest("SHA256WithRSA",
CertTools.stringToBcX509Name("CN=NOUSED"), keys.getPublic(), null, keys.getPrivate());
//Print Privatekey
//System.out.println(keys.getPrivate().toString());
CertificateResponse certenv = ws.certificateRequest(user1,
new String(Base64.encode(pkcs10.getEncoded())),
CertificateHelper.CERT_REQ_TYPE_PKCS10,
null,
CertificateHelper.RESPONSETYPE_CERTIFICATE);
//Certificate certenv = ejbcaraws.pkcs10Req("WSTESTUSER1","foo123",new
//String(Base64.encode(pkcs10.getEncoded())),null);
return certenv.getCertificate ();
}catch (Exception e) {}
并以此保存证书:
File file = new File(path+"/"+ x509Cert.getSubjectDN().toString().replace("CN=", "") +".cer");
FileOutputStream os = new FileOutputStream(file);
//os.write("-----BEGIN CERTIFICATE-----\n".getBytes("US-ASCII"));
//os.write(Base64.encode(x509Cert.getEncoded(), true));
//os.write("-----END CERTIFICATE-----".getBytes("US-ASCII"));
//os.close();
PEMWriter pemWriter = new PEMWriter(new PrintWriter(os));
pemWriter.writeObject(x509Cert);
pemWriter.flush();
pemWriter.close();