从 x509certificate2 对象导出 pem 格式的公钥

Ami*_*och 3 x509certificate2 public-key-encryption pem cer public-key

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

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

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

但我的问题是关于公钥的。设 pubKey 是从 x509certificate2 对象以 .cer 格式导出的公钥,是该密钥的 pem 格式,将是:

------BEGIN PUBLIC KEY-----
pubKey...
------END PUBLIC KEY------
Run Code Online (Sandbox Code Playgroud)

以 64 为基数编码?

谢谢 :)

bar*_*njs 5

为公钥。令 pubKey 为从 x509certificate2 对象以 .cer 格式导出的公钥

Talking about a ".cer format" only applies when you have the whole certificate; and that's all that an X509Certificate2 will export as. (Well, or a collection of certificates, or a collection of certificates with associated private keys).

Edit (2021-08-20):

  • Starting in .NET 6 you can use cert.PublicKey.ExportSubjectPublicKeyInfo() to get the DER-encoded SubjectPublicKeyInfo.
  • In .NET Core 3+/.NET 5+ you can use cert.GetRSAPublicKey()?.ExportSubjectPublicKeyInfo() (or whatever algorithm your key is)
  • In .NET 5+ you can turn those answers into PEM with PemEncoding.Write("PUBLIC KEY", spki)
  • Regardless of your .NET/.NET Core/.NET Framework version you can use the System.Formats.Asn1 package with AsnWriter to avoid the BuildSimpleDerSequence work (published 2020-11-09).

-- Original answer continues --

Nothing built in to .NET will give you the DER-encoded SubjectPublicKeyInfo block of the certificate, which is what becomes "PUBLIC KEY" under a PEM encoding.

You can build the data yourself, if you want. For RSA it's not too bad, though not entirely pleasant. The data format is defined in 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  }
Run Code Online (Sandbox Code Playgroud)

https://www.rfc-editor.org/rfc/rfc3279#section-2.3.1 describes how RSA keys, in particular are to be encoded:

The rsaEncryption OID is intended to be used in the algorithm field of a value of type AlgorithmIdentifier. The parameters field MUST have ASN.1 type NULL for this algorithm identifier.

The RSA public key MUST be encoded using the ASN.1 type RSAPublicKey:

RSAPublicKey ::= SEQUENCE {
    modulus            INTEGER,    -- n
    publicExponent     INTEGER  }  -- e
Run Code Online (Sandbox Code Playgroud)

这些结构背后的语言是 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,
    };
}
Run Code Online (Sandbox Code Playgroud)

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

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

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