2015-10-12 115 views
0

有没有什么方法可以将文件返回给客户端,使用.p12扩展名(base64编码的字符串,稍后在客户端解码并保存为.p12扩展名)到PKCS12密钥库?我有创建根证书,客户端证书和设置keyentry到PKCS12密钥库的代码,但我不想在文件系统上有.p12文件,只是为了生成它并将其返回给客户端。谢谢!创建根证书的将.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保存,浏览器说无效或损坏的文件。

在此先感谢!

回答

1

只需使用一个ByteArrayOutputStream,而不是FileOutputStream中存储P12:

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
store.store(baos, passwd); 
byte[] p12Bytes = baos.toByteArray(); 
String p12Base64 = new String(Base64.encode(p12Bytes)); 
+0

谢谢Omikron。 – user5437680