我使用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();
答案 0 :(得分:1)
我从不使用EJBCA
,但是如果您拥有证书和私钥,并且想要创建PKCS12
,则可以使用setKeyEntry(String alias,byte[] key,Certificate[] chain)
中的java.security.KeyStore
方法添加条目,然后store(OutputStream stream, char[] password)
方法将PKCS12
保存在文件中(有关详细信息,请查看API)。您的代码可能类似于:
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
public class SamplePKCS12 {
public static void main(String args[]) throws Exception {
String alias = // the alias for your key...
PrivateKey key = // your private key
Certificate[] chain = // an array with your EE certificate to your CA issuer
// create keystore
KeyStore keystore = KeyStore.getInstance("PKCS12");
// add your key and cert
keystore.setKeyEntry(alias, key.getEncoded(), chain);
// save the keystore to file
keystore.store(new FileOutputStream("/tmp/keystore.p12"), "yourPin".toCharArray());
}
}
注意我假设你的证书和私钥正如你在问题中所说的那样。要使用PKCS12
,您需要SunJSSE
提供商(默认情况下通常会加载),或者您可以使用BouncyCastle
提供商。
希望这有帮助,