2015-10-12 67 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