You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C#中获取X509Certificate中签名的时间戳

获取文件签名的日期与时间

你当前用X509Certificate2.CreateFromSignedFile拿到的是证书本身的信息,而签名时间是嵌入在文件的签名数据里,并非证书的固有属性。要获取它,得用System.Security.Cryptography.Pkcs命名空间下的SignedCms类来解析签名内容,具体实现如下:

完整代码示例

using System;
using System.IO;
using System.Security.Cryptography.Pkcs;

public DateTime? GetSigningDateTime(string fileName)
{
    try
    {
        // 读取目标文件的二进制内容
        byte[] fileContent = File.ReadAllBytes(fileName);
        
        // 初始化SignedCms对象,指定非分离式签名(签名数据嵌入文件中)
        SignedCms signedCms = new SignedCms(new ContentInfo(fileContent), detached: false);
        
        // 解码文件中的签名数据
        signedCms.Decode(fileContent);
        
        // 遍历签名者信息(多数场景下一个文件只有一个签名)
        foreach (SignerInfo signerInfo in signedCms.SignerInfos)
        {
            // 遍历签名属性,找到标识为SignerTime的属性
            foreach (CryptographicAttributeObject attr in signerInfo.SignedAttributes)
            {
                // "1.2.840.113549.1.9.5"是SignerTime的标准OID标识
                if (attr.Oid.Value == "1.2.840.113549.1.9.5")
                {
                    AsnEncodedData timeValue = attr.Values[0];
                    DateTime signingTime = DateTime.Parse(timeValue.Format(true));
                    return signingTime;
                }
            }
        }
        
        return null; // 未找到有效签名时间
    }
    catch (Exception ex)
    {
        Console.WriteLine($"解析签名信息时出错:{ex.Message}");
        return null;
    }
}

关键说明

  • SignedCms是专门处理PKCS#7签名数据的类,能精准提取文件签名的元数据,包括签名时间。
  • 要确保项目引用了System.Security.Cryptography.Pkcs程序集(.NET Core/.NET 5+默认已包含,.NET Framework需手动添加引用)。
  • 若文件存在多个签名,代码会返回第一个找到的签名时间,你可根据需求调整遍历逻辑。

调用示例

string targetFile = "你的文件路径";
DateTime? signingTime = GetSigningDateTime(targetFile);
if (signingTime.HasValue)
{
    Console.WriteLine($"文件签名时间:{signingTime.Value:yyyy-MM-dd HH:mm:ss}");
}
else
{
    Console.WriteLine("未检测到有效签名或签名时间");
}

内容的提问来源于stack exchange,提问作者skysurfer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:16:02