【问题标题】:How to open serialized .Net X509Certificate2 in OpenSSL?如何在 OpenSSL 中打开序列化的 .Net X509Certificate2?
【发布时间】:2014-04-23 01:16:33
【问题描述】:

我需要让两个软件互操作。一种是 .NET 中的 Web 服务,它返回 X509Certificate2 实例的原始二进制数据,采用 Base64 编码。另一个是可以使用 OpenSSL 使用从 web 服务接收到的二进制证书的 android 应用程序。

但是,OpenSSL 总是回答数据不是有效的证书格式。我尝试将 Base64 字符串包装在适用的 PEM 页眉和页脚中,但没有效果。

有人对这种互操作性有任何经验吗?

【问题讨论】:

    标签: .net openssl certificate x509certificate x509certificate2


    【解决方案1】:

    此方法将 X509Certificate2 转换为 C# 中的 PEM 格式:

    public static string ConvertToPEM(X509Certificate2 cert)
    {
        if (cert == null)
            throw new ArgumentNullException("cert");
    
        string base64 = Convert.ToBase64String(cert.RawData).Trim();
    
        string pem = "-----BEGIN CERTIFICATE-----" + Environment.NewLine;
    
        do
        {
            pem += base64.Substring(0, 64) + Environment.NewLine;
            base64 = base64.Remove(0, 64);
        }
        while (base64.Length > 64);
    
        pem += base64 + Environment.NewLine + "-----END CERTIFICATE-----";
    
        return pem;
    }
    

    此方法使用 OpenSSL 解析 C 语言中的 PEM 编码证书:

    X509* parse_pem_cert(const char* buffer, int buffer_len)
    {
        X509* cert = NULL;
        BIO* bio = NULL;
    
        if ((NULL == buffer) || (buffer_len < 1))
            return NULL;
    
        bio = BIO_new_mem_buf((char *) buffer, buffer_len);
        if (NULL == bio)
            return NULL;
    
        cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
        if (NULL == cert)
        {
            BIO_free(bio);
            return NULL;
        }
    
        BIO_free(bio);
        return cert;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      • 2011-04-02
      相关资源
      最近更新 更多