.net 如何使用C#获取X509Certificate2对象的签名?

brvekthn  于 2022-12-30  发布在  .NET
关注(0)|答案(3)|浏览(186)

我需要用C#从证书中获取签名和用于创建该签名的算法。
我可以这么做吗?如果可以,怎么做?

p8ekf7hl

p8ekf7hl1#

我现在正在开发类似功能的应用程序。我真的很失望为什么微软没有添加属性签名到X509Certificate2类
我知道怎么用弹跳城堡
从那里开始
然后添加代码

using System;
using System.Security.Cryptography.X509Certificates;
using bcrypto = Org.BouncyCastle.X509;

var cert = new X509Certificate2("c:\\temp\\0c50000343119659.cer");
var certParser = new bcrypto.X509CertificateParser();
var privateCertBouncy = certParser.ReadCertificate(cert.GetRawCertData());
var xx = privateCertBouncy.GetSignature();
Array.Reverse(xx);
//Signature
Console.WriteLine(BitConverter.ToString(xx));
//algorithm
Console.WriteLine(privateCertBouncy.SigAlgName);
Console.ReadLine();
8aqjt8rx

8aqjt8rx2#

你只能去充气城堡了
https://github.com/bcgit/bc-csharp/blob/master/crypto/src/x509/X509Certificate.cs#L240
它的X509Certificate类允许您访问此属性。

3bygqnnd

3bygqnnd3#

可以将AsnDecoder与RFC3280第4.1节中的X509 v3结构信息一起使用。将此函数的输出与openssl x509 -noout -text -in <pem file>进行比较

/// <summary>
/// RFC3280 Section 4.1
/// Depth 1 of the X509 v3 cert is
/// Certificate  ::=  SEQUENCE  {
///     tbsCertificate TBSCertificate,
///     signatureAlgorithm   AlgorithmIdentifier,
///     signatureValue BIT STRING
/// }
///
/// https://www.rfc-editor.org/rfc/rfc3280#section-4.1
/// </summary>
public static byte[] Signature(this X509Certificate2 certificate)
{
    var signedData = certificate.RawDataMemory;
    AsnDecoder.ReadSequence(
        signedData.Span,
        AsnEncodingRules.BER,
        out var offset,
        out var length,
        out _
    );

    var certificateSpan = signedData.Span[offset..(offset + length)];
    AsnDecoder.ReadSequence(
        certificateSpan,
        AsnEncodingRules.BER,
        out var tbsOffset,
        out var tbsLength,
        out _
    );

    var offsetSpan = certificateSpan[(tbsOffset + tbsLength)..];
    AsnDecoder.ReadSequence(
        offsetSpan,
        AsnEncodingRules.BER,
        out var algOffset,
        out var algLength,
        out _
    );

    return AsnDecoder.ReadBitString(
        offsetSpan[(algOffset + algLength)..],
        AsnEncodingRules.BER,
        out _,
        out _
    );
}

相关问题