首页 文章

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

提问于
浏览
0

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

我正在尝试从c#格式的PEM格式的x509certificate2对象中导出公钥 .

据我所知,cer格式与pem格式的证书之间的区别仅在于页眉和页脚(如果我理解正确的话,基本64中的.cer格式的证书应该是someBase64String,并且在pem格式中它是相同的字符串包括开头和结尾页眉和页脚) .

但我的问题是公钥 . 让pubKey成为从x509certificate2对象导出的.cer格式的公钥,是这个键的pem格式,将是:------ BEGIN PUBLIC KEY ----- pubKey ... ----- -END PUBLIC KEY ------以base 64编码?

谢谢 :)

1 回答

  • 1

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

    谈论“.cer格式”仅适用于拥有整个证书的情况;这就是X509Certificate2将导出的全部内容 . (好吧,或证书集合,或带有相关私钥的证书集合) .

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

    如果需要,您可以自己构建数据 . 对于RSA而言,它并不是太糟糕,尽管并不完全令人愉快 . 数据格式在https://tools.ietf.org/html/rfc3280#section-4.1中定义:

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

    https://tools.ietf.org/html/rfc3279#section-2.3.1描述了如何编码RSA密钥:

    rsaEncryption OID旨在用于AlgorithmIdentifier类型的值的算法字段中 . 对于该算法标识符,参数字段必须具有ASN.1类型NULL . RSA公钥必须使用ASN.1类型RSAPublicKey进行编码:RSAPublicKey :: = SEQUENCE {
    模数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(byte []) switch语句中的值 .

    我的SEQUENCE和BIT STRING构建器绝对可以更高效(哦,看看所有那些糟糕的数组),但这对于非关键性的东西就足够了 .

    要检查结果,可以将输出粘贴到 openssl rsa -pubin -text -noout ,如果它打印出错误以外的任何内容,则表明您已为RSA密钥编写了合法编码的"PUBLIC KEY"编码 .

相关问题