【问题标题】:exporting a public key in pem format from x509certificate2 object从 x509certificate2 对象导出 pem 格式的公钥
【发布时间】:2017-12-30 21:38:02
【问题描述】:

我是这个主题的新手,我对 PEM 格式的公钥和 CER 格式的公钥之间的区别感到困惑。

我正在尝试在 c# 代码中以 PEM 格式从 x509certificate2 对象导出公钥。

据我了解,cer 格式的证书与 pem 格式的证书之间的区别仅在于页眉和页脚 (如果我理解正确,.cer 格式的 base 64 证书应该是 someBase64String 和 pem 格式它是相同的字符串,包括开始和结束页眉和页脚)。

但我的问题是关于公钥。 让 pubKey 成为从 x509certificate2 对象以 .cer 格式导出的公钥, 是这个键的 pem 格式,将是:

------BEGIN PUBLIC KEY-----
pubKey...
------END PUBLIC KEY------

以 base 64 编码?

谢谢:)

【问题讨论】:

    标签: public-key-encryption public-key pem x509certificate2 cer


    【解决方案1】:

    用于公钥。让 pubKey 成为从 x509certificate2 对象以 .cer 格式导出的公钥

    仅当您拥有整个证书时才适用“.cer 格式”;这就是 X509Certificate2 将导出的所有内容。 (嗯,或者证书集合,或者具有相关私钥的证书集合)。

    编辑(2021-08-20)

    • 从 .NET 6 开始,您可以使用 cert.PublicKey.ExportSubjectPublicKeyInfo() 获取 DER 编码的 SubjectPublicKeyInfo。
    • 在 .NET Core 3+/.NET 5+ 中,您可以使用 cert.GetRSAPublicKey()?.ExportSubjectPublicKeyInfo()(或任何您的密钥算法)
    • 在 .NET 5+ 中,您可以使用 PemEncoding.Write("PUBLIC KEY", spki) 将这些答案转换为 PEM
    • 无论您的 .NET/.NET Core/.NET Framework 版本如何,您都可以使用带有 AsnWriterSystem.Formats.Asn1 包来避免 BuildSimpleDerSequence 工作(2020 年 11 月 9 日发布)。

    -- 原答案继续--

    .NET 内置的任何内容都不会为您提供证书的 DER 编码的 SubjectPublicKeyInfo 块,这就是 PEM 编码下的“公钥”。

    如果需要,您可以自己构建数据。对 RSA 来说,这还不算太糟糕,尽管并不完全令人愉快。数据格式定义在https://www.rfc-editor.org/rfc/rfc3280#section-4.1:

    SubjectPublicKeyInfo  ::=  SEQUENCE  {
        algorithm            AlgorithmIdentifier,
        subjectPublicKey     BIT STRING  }
    
    AlgorithmIdentifier  ::=  SEQUENCE  {
        algorithm               OBJECT IDENTIFIER,
        parameters              ANY DEFINED BY algorithm OPTIONAL  }
    

    https://www.rfc-editor.org/rfc/rfc3279#section-2.3.1 描述了如何对 RSA 密钥进行编码,尤其是:

    rsaEncryption OID 旨在用于算法字段 类型为 AlgorithmIdentifier 的值。参数字段必须 此算法标识符的 ASN.1 类型为 NULL。

    RSA 公钥必须使用 ASN.1 类型 RSAPublicKey 进行编码:

    RSAPublicKey ::= SEQUENCE {
        modulus            INTEGER,    -- n
        publicExponent     INTEGER  }  -- e
    

    这些结构背后的语言是 ASN.1,由 ITU X.680 定义,它们被编码为字节的方式由 ITU X.690 的可分辨编码规则 (DER) 规则集涵盖。

    .NET 实际上给了你很多这样的部分,但你必须组装它们:

    private static string BuildPublicKeyPem(X509Certificate2 cert)
    {
        byte[] algOid;
    
        switch (cert.GetKeyAlgorithm())
        {
            case "1.2.840.113549.1.1.1":
                algOid = new byte[] { 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 };
                break;
            default:
                throw new ArgumentOutOfRangeException(nameof(cert), $"Need an OID lookup for {cert.GetKeyAlgorithm()}");
        }
    
        byte[] algParams = cert.GetKeyAlgorithmParameters();
        byte[] publicKey = WrapAsBitString(cert.GetPublicKey());
    
        byte[] algId = BuildSimpleDerSequence(algOid, algParams);
        byte[] spki = BuildSimpleDerSequence(algId, publicKey);
    
        return PemEncode(spki, "PUBLIC KEY");
    }
    
    private static string PemEncode(byte[] berData, string pemLabel)
    {
        StringBuilder builder = new StringBuilder();
        builder.Append("-----BEGIN ");
        builder.Append(pemLabel);
        builder.AppendLine("-----");
        builder.AppendLine(Convert.ToBase64String(berData, Base64FormattingOptions.InsertLineBreaks));
        builder.Append("-----END ");
        builder.Append(pemLabel);
        builder.AppendLine("-----");
    
        return builder.ToString();
    }
        
    private static byte[] BuildSimpleDerSequence(params byte[][] values)
    {
        int totalLength = values.Sum(v => v.Length);
        byte[] len = EncodeDerLength(totalLength);
        int offset = 1;
    
        byte[] seq = new byte[totalLength + len.Length + 1];
        seq[0] = 0x30;
    
        Buffer.BlockCopy(len, 0, seq, offset, len.Length);
        offset += len.Length;
    
        foreach (byte[] value in values)
        {
            Buffer.BlockCopy(value, 0, seq, offset, value.Length);
            offset += value.Length;
        }
    
        return seq;
    }
    
    private static byte[] WrapAsBitString(byte[] value)
    {
        byte[] len = EncodeDerLength(value.Length + 1);
        byte[] bitString = new byte[value.Length + len.Length + 2];
        bitString[0] = 0x03;
        Buffer.BlockCopy(len, 0, bitString, 1, len.Length);
        bitString[len.Length + 1] = 0x00;
        Buffer.BlockCopy(value, 0, bitString, len.Length + 2, value.Length);
        return bitString;
    }
    
    private static byte[] EncodeDerLength(int length)
    {
        if (length <= 0x7F)
        {
            return new byte[] { (byte)length };
        }
    
        if (length <= 0xFF)
        {
            return new byte[] { 0x81, (byte)length };
        }
    
        if (length <= 0xFFFF)
        {
            return new byte[]
            {
                0x82,
                (byte)(length >> 8),
                (byte)length,
            };
        }
    
        if (length <= 0xFFFFFF)
        {
            return new byte[]
            {
                0x83,
                (byte)(length >> 16),
                (byte)(length >> 8),
                (byte)length,
            };
        }
    
        return new byte[]
        {
            0x84,
            (byte)(length >> 24),
            (byte)(length >> 16),
            (byte)(length >> 8),
            (byte)length,
        };
    }
    

    DSA 和 ECDSA 键的 AlgorithmIdentifier.parameters 值更复杂,但 X509Certificate 的 GetKeyAlgorithmParameters() 恰好将它们返回正确格式,因此您只需写下它们的 OID(字符串)查找键和它们的 OID(字节 [ ]) switch 语句中的编码值。

    我的 SEQUENCE 和 BIT STRING 构建器肯定会更高效(哦,看看那些糟糕的数组),但这对于性能不重要的东西就足够了。

    要检查您的结果,您可以将输出粘贴到openssl rsa -pubin -text -noout,如果它打印出除错误以外的任何内容,您已经为 RSA 密钥进行了合法编码的“PUBLIC KEY”编码。

    【讨论】:

      【解决方案2】:

      从 .NET Core 3.0(和 .NET Standard 2.1)开始,您可以像这样使用 ExportSubjectPublicKeyInfo 方法:

      certificate.PublicKey.Key.ExportSubjectPublicKeyInfo()
      

      如果PublicKey.Key 抛出异常(仅支持RSA 和DSA),请使用ECDsaCertificateExtensions.GetECDsaPublicKeyRSACertificateExtensions.GetRSAPublicKeyDSACertificateExtensions.GetDSAPublicKey 之一。

      【讨论】:

        【解决方案3】:

        就像 bartonjs 所说:“SubjectPublicKeyInfo 在 PEM 编码下变为“PUBLIC KEY”,.NET 内置的任何内容都不会为您提供 DER 编码的 SubjectPublicKeyInfo 证书块。”

        幸运的是,Bouncy Castle 来了救援,只需几行即可从 X509Certificate2 中提取 SubjectPublicKeyInfo(即 PEM 证书的公钥)

        Org.BouncyCastle.X509.X509Certificate bcert = new Org.BouncyCastle.X509.X509Certificate(x509Certificate2.RawData);
        var publicKeyInfoBytes = bcert.CertificateStructure.SubjectPublicKeyInfo.GetDerEncoded();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-03-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-10-20
          • 1970-01-01
          相关资源
          最近更新 更多