Convert SSL .pem to .p12 with or without OpenSSL

后端 未结 5 563
盖世英雄少女心
盖世英雄少女心 2021-01-30 23:18

I get external .pem files that need to be converted to .p12 files - I add a username and password in the process. (I need to do this to utilize a thir

5条回答
  •  星月不相逢
    2021-01-31 00:01

    This solutions is an adaptation of @sascha-arthur's to accomodate for:

    • Handles edge-case where PrivateKey format is not as expected.
    • Gracefully handle scenario where public key is not available
    • Fixed a few minor redundancies and formatting

    The code:

    String alias="myalias";
    char[] password = "mypassword".toCharArray();
    
    // Private Key
    PEMParser pem = new PEMParser(new FileReader(keyFile));
    Object parsedObject = pem.readObject();
    
    PrivateKeyInfo privateKeyInfo = parsedObject instanceof PEMKeyPair ? ((PEMKeyPair)parsedObject).getPrivateKeyInfo() : (PrivateKeyInfo)parsedObject;
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded());
    KeyFactory factory = KeyFactory.getInstance("RSA");
    PrivateKey key = factory.generatePrivate(privateKeySpec);
    
    List certs = new ArrayList<>();
    X509CertificateHolder certHolder = (X509CertificateHolder)pem.readObject();
    if(certHolder != null) {
        certs.add(new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder));
    }
    
    // Certificate
    pem = new PEMParser(new FileReader(certFile));
    while((certHolder = (X509CertificateHolder)pem.readObject()) != null) {
        certs.add(new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder));
    }
    
    // Keystore
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(null);
    
    for (int i = 0; i < certs.size(); i++) {
        ks.setCertificateEntry(alias + "_" + i, certs.get(i));
    }
    
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(null);
    keyStore.setKeyEntry(alias, key, password, certs.toArray(new X509Certificate[certs.size()]));
    

    For this to work with a LetsEncrypt certificate, you'll need to use the following files:

    • privkey.pem
    • fullchain.pem

提交回复
热议问题