Convert SSL .pem to .p12 with or without OpenSSL

后端 未结 5 549
盖世英雄少女心
盖世英雄少女心 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:20

    Based on @MugglesMerriweather 's answer, an updated version to v1.51 is the following:

    public static byte[] convertPEMToPKCS12(final String keyFile, final String cerFile,
            final String password)
            throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException
        {
            // Get the private key
            FileReader reader = new FileReader(keyFile);
    
            PEMParser pem = new PEMParser(reader);
            PEMKeyPair pemKeyPair = ((PEMKeyPair)pem.readObject());
            JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter().setProvider("SC");
            KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);
    
            PrivateKey key = keyPair.getPrivate();
    
            pem.close();
            reader.close();
    
            // Get the certificate
            reader = new FileReader(cerFile);
            pem = new PEMParser(reader);
    
            X509CertificateHolder certHolder = (X509CertificateHolder) pem.readObject();
            java.security.cert.Certificate X509Certificate =
                new JcaX509CertificateConverter().setProvider("SC")
                    .getCertificate(certHolder);
    
            pem.close();
            reader.close();
    
            // Put them into a PKCS12 keystore and write it to a byte[]
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            KeyStore ks = KeyStore.getInstance("PKCS12");
            ks.load(null);
            ks.setKeyEntry("alias", (Key) key, password.toCharArray(),
                new java.security.cert.Certificate[]{X509Certificate});
            ks.store(bos, password.toCharArray());
            bos.close();
            return bos.toByteArray();
        }
    

提交回复
热议问题