从RFC 3852(和RFC 3161)中,我知道签名值存储为TimestampToken的SignerInfo类型的属性(这是Signed Data内容类型)。

如何从Bouncy Castle(在C#中)的TimeStampToken实例中获取该签名值?

最佳答案

您可以将类与辅助方法一起使用:

public static class TimeStampTokenHelper
{
    public static IEnumerable<SignedData> GetTimeStampTokensAsSignedData(byte[] input)
    {
        var cmsInputStream = new Asn1InputStream(input);
        var asn1Object = cmsInputStream.ReadObject();
        Assert.IsNotNull(asn1Object);

        var rootSequence = Asn1Sequence.GetInstance(asn1Object);
        var signedData = GetSignedData(rootSequence);
        return GetTimeStampTokensFromSignedData(signedData);
    }

    private static SignedData GetSignedData(Asn1Sequence sequence)
    {
        var rootContent = ContentInfo.GetInstance(sequence);
        Assert.That(rootContent.ContentType.Id, Is.EqualTo("1.2.840.113549.1.7.2")); // signedData
        var signedData = SignedData.GetInstance(rootContent.Content);
        return signedData;
    }

    private static IEnumerable<SignedData> GetTimeStampTokensFromSignedData(SignedData signedData)
    {
        return GetTimeStampTokensFromSignerInfos(signedData.SignerInfos);
    }

    private static IEnumerable<SignedData> GetTimeStampTokensFromSignerInfos(Asn1Set signerInfos)
    {
        var timestampTokens = signerInfos
            .OfType<Asn1Sequence>()
            .SelectMany(GetTimeStampTokensFromSignerInfo);
        return timestampTokens;
    }

    private static IEnumerable<SignedData> GetTimeStampTokensFromSignerInfo(Asn1Sequence signerInfoSequence)
    {
        var signerInfo = SignerInfo.GetInstance(signerInfoSequence);
        var result = signerInfo.UnauthenticatedAttributes.ToArray()
            .Select(Asn1Sequence.GetInstance)
            .Where(x => ((DerObjectIdentifier)x.GetObjectAt(0)).Id == "1.2.840.113549.1.9.16.2.14")
            .Select(x => GetSignedData(Asn1Sequence.GetInstance(Asn1Set.GetInstance(x.GetObjectAt(1)).GetObjectAt(0))));
        return result;
    }


TimeStampTokenHelper.GetTimeStampTokensAsSignedData辅助方法将提取时间戳记令牌作为SignedData结构。您可以对返回的SignedData数据进行所有所需的操作。

这是如何从SignerInfo提取签名的示例:

var signatures = TimeStampTokenHelper.GetTimeStampTokensAsSignedData(cadesTBytes)
    .SelectMany(token => token.SignerInfos.ToArray().Select(SignerInfo.GetInstance))
    .Select(signerInfo => signerInfo.EncryptedDigest);


最后提示:


您可以使用free online ASN.1 viewer来了解Cades T签名的结构
您可以使用Org.BouncyCastle.Asn1.Utilities.Asn1Dump.DumpAsString方法转储Bouncycastle的ASN.1对象的字符串表示形式


希望这可以帮助。

关于c# - 如何在TimeStampToken(Bouncy CaSTLe)中获得签名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48434163/

10-17 00:10