1

A CA gives me a P12 which I want to convert to PEM inside a jvm.

Yes using openssl command works:

openssl pkcs12 -in jack.p12 -out jack.pem -nodes -clcerts

But then it gets ugly getting key and keystore passwords into the openssl program from java not to mention unsecure.

so BouncyCastle seems to be best crypto API for java... How could it be done (convert P12 to PEM) using bouncy...

4

2 回答 2

1

这是一个例子:

  private File createPem(final Certificate certP12, final String name) {
    File file = new File(getFileName(name, "pem"));
    FileWriter fileWriter;
    try {
        fileWriter = new FileWriter(file);

        PEMWriter pemWriter = new PEMWriter(fileWriter);
        pemWriter.writeObject(certP12);
        pemWriter.flush();

        pemWriter.close();
        fileWriter.close();
    } catch (IOException e) {
        log.error("", e);
    }

    return file;
  }
于 2012-09-19T17:51:24.883 回答
0
  1. 将证书加载为 Org.BouncyCastle.X509.X509Certificate
  2. 转换为 pem。
public static Org.BouncyCastle.X509.X509Certificate ImportCertFromPfx(string path, string password)
        {
            Pkcs12Store store = new Pkcs12StoreBuilder().Build();
            store.Load(File.OpenRead(path), password.ToCharArray());
            string alias = null;
            foreach (string str in store.Aliases)
            {
                if (store.IsKeyEntry(str))
                    alias = str;
            }
            if (alias == null)
            {
                Console.WriteLine("alias is null");
            }
            else
                Console.WriteLine(alias);

            X509CertificateEntry certEntry = store.GetCertificate(alias);
            Org.BouncyCastle.X509.X509Certificate x509cert = certEntry.Certificate;
            return x509cert;
        }
Org.BouncyCastle.X509.X509Certificate x509cert = ImportCertFromPfx(p12path, p12password);

StringBuilder CertPem = new StringBuilder();
PemWriter CSRPemWriter = new PemWriter(new StringWriter(CertPem));
CSRPemWriter.WriteObject(x509cert);
CSRPemWriter.Writer.Flush();

//get Cert text
var CertPemText = CertPem.ToString();
Console.WriteLine(CertPemText);
于 2021-04-25T06:19:23.243 回答