BouncyCastle可以将P12转换为PEM

时间:2012-08-23 15:34:27

标签: certificate x509certificate bouncycastle

CA给了我一个P12,我想在jvm中转换为PEM。

是的,使用openssl命令工作:

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

但是,从java获取密钥和密钥库密码进入openssl程序会更难以提及不安全。

所以BouncyCastle似乎是java最好的加密API ... 如何使用弹性来完成(将P12转换为PEM)...

2 个答案:

答案 0 :(得分:2)

以下是一个例子:

  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;
  }

答案 1 :(得分: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);