【问题标题】:Create an X509Certicate from a DER decoded String从 DER 解码的字符串创建 X509Certicate
【发布时间】:2012-07-13 05:05:49
【问题描述】:

我有一个 X509Certificate,我将其写入/打印到文件中,如下所示。 (我没有写编码字节,因为我想读取证书的内容)

X509Certificate cer = generateCertificate(); // cer is DER encoded
writeToFile( cer.toString() ); // cer.toString() converts DER to UTF/ASCII???

稍后我想将该文件(上图)作为字符串读取并创建一个新的 X509Certificate。

String cerStr = readCerFromFile(); // Read what is written above. In ASCII/ UTF format
ByteArrayInputStream bais = null;
try {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    bais = new ByteArrayInputStream(cerStr.getBytes());
    return (X509Certificate) cf.generateCertificate(bais);
} ...

这会引发以下异常。

Java.security.cert.CertificateParsingException: Invalid DER-encoded certificate data

很明显,我没有将 cerStr 转换为 DER 格式(而且我不知道是否可以转换为 DER )。谁能解释一下如何从未编码的字符串创建 X509Certcate。

提前致谢!

【问题讨论】:

  • .toString() 没有任何意义。您应该从cer.getEncoded() 写入编码字节。使用X509Certificate.toString 只是在自取其辱。所以不要那样做,至少不要持久化证书。
  • 感谢 GregS。 .toString() 可以解码和打印 DER 编码的证书吗?
  • 可以目视检查内容。

标签: cryptography public-key-encryption x509


【解决方案1】:

简短的回答:你不能。 DER 编码了太多无法轻松转换为 String 的细节。正如 GregS 在 cmets 中解释的那样,您最好使用 cer.getEncoded() 简单地保存 DER 编码的证书。

如果您想查看证书的内容,只需使用您的操作系统识别的文件扩展名保存它并双击它。如果您想使用命令行方法打印纯文本信息,请使用例如打开ssl:

openssl x509 -text -noout -inform DER -in mycertificate.crt

在许多 Unix 风格(Linux、Apple)中是标准包含或可选的,也可以在 Windows 上运行。

【讨论】:

  • 当然,您也可以在 Java 中创建 CLI 应用程序。只需读取证书/使用 X509 证书工厂对其进行解码并打印出证书大约需要 10 分钟的工作时间,但随后您需要处理安装、shell 脚本创建等。
  • Java keytool 也可以使用,不过它只在 SDK 中可用,而不是运行时。
  • 感谢@erickson 对这个答案的拼写检查,我一定是困了。
【解决方案2】:

当您将证书作为原始数据 cert.getEncoded()(在 .Net 中为 cert.RawData)时,它以 DER 格式编码。通俗地说,它只是证书的特殊二进制表示。

但存在良好的证书字符串表示。您可以将 DER 中证书的原始表示形式转换为 Base64 格式的字符串。我不知道 JAVA,所以在 .Net 中它看起来像这样Convert.ToBase64dString(cert.RawData)。

您可以将两种格式的证书保存到扩展名为 .cer 或 .crt 的文件中,然后使用标准操作系统证书查看器打开它。

【讨论】:

    【解决方案3】:

    一个糟糕的男人回答(我会非常低水平)

    // 创建 pfx 字节流... byte[] selfSigned = CertificateCreator.CreateSelfSignCertificatePfx(distinguishedName, 新日期时间(2013, 4, 1), 新日期时间(2013, 12, 31), 不安全密码);

    // 创建一个证书实例 X509Certificate2 cert = new X509Certificate2(selfSigned, insecurePassword);

    // 导出为 .cer [DER] selfSigned = cert.Export(X509ContentType.Cert);

    // 写入文件.. System.IO.File.WriteAllBytes(certificateFilename+".cer"), selfSigned);

    【讨论】:

    • 感谢大卫的回答
    【解决方案4】:

    在Java中你可以做到

        String sCert = javax.xml.bind.DatatypeConverter.printBase64Binary(certificate.getEncoded()); 
    

    在.Net中

    Convert.ToBase64String(Certificate.RawData);
    

    【讨论】:

      猜你喜欢
      • 2012-01-17
      • 2012-10-24
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多