有没有办法将文件返回到客户端,扩展名为.p12(base64编码的字符串,稍后在客户端解码并以.p12扩展名保存),而不将其存储到PKCS12密钥库?我有创建根证书,客户端证书和设置keyentry到PKCS12密钥库的代码,但我不想在文件系统上有.p12文件,只是为了生成它并将其返回给客户端。谢谢!
创建根证书的简化代码:
public static void createRootCertificate(PublicKey pubKey, PrivateKey privKey) {
certGen.setSerialNumber(...);
certGen.setIssuerDN(...);
certGen.setNotBefore(...);
certGen.setNotAfter(...);
certGen.setSubjectDN(...);
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("SHA1WithRSA");
// add extensions, key identifier, etc.
X509Certificate cert = certGen.generateX509Certificate(privKey);
cert.checkValidity(new Date());
cert.verify(pubKey);
}
创建后,根证书及其私钥将保存到受信任的存储区。
在生成客户端证书的服务中,我从可信商店读取根证书并生成客户端证书:
public static Certificate createClientCertificate(PublicKey pubKey) {
PrivateKey rootPrivateKey = ... //read key from trusted store
X509Certificate rootCertificate = ... //read certificate from trusted store
certGen.setSerialNumber(...);
certGen.setIssuerDN(...); // rootCertificate.getIssuerDN ...
certGen.setNotBefore(...);
certGen.setNotAfter(...);
certGen.setSubjectDN(...);
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("SHA1WithRSA");
// add extensions, issuer key, etc.
X509Certificate cert = certGen.generateX509Certificate(rootPrivateKey);
cert.checkValidity(new Date());
cert.verify(rootCertificate.getPublicKey(););
return cert;
}
主要课程如下:
public static void main(String[] args) {
// assume I have all needed keys generated
createRootCertificate(rootPubKey, rootPrivKey);
X509Certificate clientCertificate = createClientCertificate(client1PubKey);
KeyStore store = KeyStore.getInstance("PKCS12", "BC");
store.load(null, null);
store.setKeyEntry("Client1_Key", client1PrivKey, passwd, new Certificate[]{clientCertificate});
FileOutputStream fOut = new FileOutputStream("client1.p12");
store.store(fOut, passwd);
}
在上面的代码之后,我正在阅读client1.p12,并且我正在创建该文件的Base64编码响应。当我在客户端解码响应并使用.p12扩展名保存时,一切正常,我可以将其导入浏览器。可以在不将其存储到文件的情况下完成吗?
我尝试过:
store.setKeyEntry("Client1_Key", client1PrivKey, passwd, new Certificate[]{clientCertificate});
之后:
Key key = store.getKey("Client1_Key", passwd);
但是当编码键变量时,发送到客户端然后解码它并使用.p12扩展名保存,浏览器说无效或损坏的文件。
提前致谢!
答案 0 :(得分:1)
只需使用ByteArrayOutputStream而不是FileOutputStream来存储p12:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
store.store(baos, passwd);
byte[] p12Bytes = baos.toByteArray();
String p12Base64 = new String(Base64.encode(p12Bytes));