【问题标题】:Return .p12 file to client without creating keystore file将 .p12 文件返回给客户端而不创建密钥库文件
【发布时间】:2015-10-12 22:47:52
【问题描述】:

有没有办法将文件返回给客户端,扩展名为 .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 扩展名保存,浏览器说无效或损坏的文件。

提前致谢!

【问题讨论】:

    标签: java ssl keystore pfx pkcs#12


    【解决方案1】:

    只需使用 ByteArrayOutputStream 而不是 FileOutputStream 来存储 p12:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      • 2014-02-04
      相关资源
      最近更新 更多