C# 向数字签名添加时间戳

C# 向数字签名添加时间戳,c#,timestamp,digital-signature,x509certificate,rsacryptoserviceprovider,C#,Timestamp,Digital Signature,X509certificate,Rsacryptoserviceprovider,我有一个代码,可以用A1证书在C#中成功地为字符串签名。 我需要给这个签名加一个时间戳。此时间戳需要从时间戳服务器(如 我不知道如何把时间戳放在签名上。 这不是PDF符号,而是字符串符号。 有人能帮我吗 用于签名的代码: private byte[] Sign(string text) { // Find the certificate we’ll use to sign X509Certificate2 cert = new X509Certificat

我有一个代码,可以用A1证书在C#中成功地为字符串签名。 我需要给这个签名加一个时间戳。此时间戳需要从时间戳服务器(如 我不知道如何把时间戳放在签名上。 这不是PDF符号,而是字符串符号。 有人能帮我吗

用于签名的代码:

private byte[] Sign(string text)
    {
        // Find the certificate we’ll use to sign
        X509Certificate2 cert = new X509Certificate2(@"C:\Users\1000084016.pfx", "Password");
        RSACryptoServiceProvider csp = null;

        // Get its associated CSP and private key
        csp = (RSACryptoServiceProvider)cert.PrivateKey;

        // Hash the data
        SHA1Managed sha1 = new SHA1Managed();
        UnicodeEncoding encoding = new UnicodeEncoding();

        byte[] data;
        data = encoding.GetBytes(text);

        byte[] hash = sha1.ComputeHash(data);

        // Sign the hash
        return csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
    }

时间戳由外部时间戳提供程序在包含哈希的
应用程序/时间戳查询上使用发出。您可以使用BouncyCastle构建请求(参见示例)


要将时间戳结果嵌入签名,不能使用基本的RSA结果。您需要使用CMS(二进制)o XMLDsig(XML)等高级签名容器,并将时间戳添加为未签名属性。请参见此处使用CMS的说明,这取决于您的数字签名的外观。如果它是XML文档,那么signedHash、timestamp和mixedHash应该有单独的字段。我会更改代码以使用CMS。CmsSigner Signer=新的CmsSigner(certificateFromFile);Signer.UnsignedAttributes.Add(新的Pkcs9SigningTime());但我无法读取Pkcs9SigningTime中的时间戳提供程序。你知道如何不用bouncy castle吗?Pkcs9SigningTime将包含本地时间。您需要使用在线http请求向TSP请求RFC3161时间戳(我在回答中发布了客户机的链接),并使用TSTInfo结构将结果包含到CMS签名中(请参阅最后一个链接)。恐怕一点也不简单。