RFC 3161 timestamps with SignedCms in .NET¶
Updated in 2026. This version fixes three bugs in the original code:
- It added the timestamp through
SignerInfo.UnsignedAttributes, which returns a copy, so the timestamp never reached the encoded signature. It now usesAddUnsignedAttribute. - It called
CheckSignature(true), which checks only the signature and skips certificate validation. It now validates the signer's certificate chain. - It mixed up the content and the signature when verifying a detached signature.
The code also uses current .NET APIs, and I ran it against DigiCert's public timestamp authority. To use these types, reference the System.Security.Cryptography.Pkcs package.
I wanted to write my own Git signing tool, and I wanted its signatures to carry an RFC 3161 timestamp. A timestamp from a trusted authority proves when you signed something, so the signature stays valid after your certificate expires.
.NET added RFC 3161 support in 2019. This article shows how to sign a message with SignedCms, add an RFC 3161 timestamp, and verify the result.
Thanks to Jeremy Barton, who helped me understand parts of this process.
My SMimeSigner project uses this code. It provides GPG-style sign and verify for X.509 certificate stores, similar to GitHub's smimesign.
Overview¶
.NET can create RFC 3161 requests and read the responses, but it does not send them to the server. That part is up to you, because the cryptography library has no knowledge of HttpClient.
When I first wrote this the API had few examples, and most of the samples online used Bouncy Castle.
Signing¶
The steps are:
- Create a
SignedCmsfor the content you want to sign. - Create a
CmsSignerwith your certificate. - Add a PKCS #9 signing time.
- Compute the signature.
- Generate a random nonce.
- Create an
Rfc3161TimestampRequestfor the signature. - Send the request to the timestamp authority and process the response.
- Add the timestamp token to the signer's unsigned attributes.
Create the SignedCms and CmsSigner¶
You need an X509Certificate2 with a private key. I load mine from the user's certificate store by thumbprint.
var contentInfo = new ContentInfo(content);
var cms = new SignedCms(contentInfo, detached);
var signer = new CmsSigner(certificate) { IncludeOption = X509IncludeOption.WholeChain };
signer.SignedAttributes.Add(new Pkcs9SigningTime());
The signing time is your own claim about when you signed. The timestamp authority's token, added later, is the trusted proof.
Compute the signature¶
cms.ComputeSignature(signer, silent: false);
Compute the signature before you request the timestamp. The timestamp authority timestamps the signature value itself.
Generate a nonce¶
The nonce is a random number that ties the authority's response to your request.
var nonce = RandomNumberGenerator.GetBytes(8);
Create the RFC 3161 request¶
Get the signer information. There should be exactly one.
var signerInfo = cms.SignerInfos[0];
var request = Rfc3161TimestampRequest.CreateFromSignerInfo(
signerInfo,
HashAlgorithmName.SHA384,
requestSignerCertificates: true,
nonce: nonce);
Send the request to the timestamp authority¶
Any HTTP client works. This example reuses one HttpClient for the life of the app.
using var body = new ReadOnlyMemoryContent(request.Encode());
body.Headers.ContentType = new MediaTypeHeaderValue("application/timestamp-query");
using var response = await httpClient.PostAsync(timestampAuthority, body, cancellationToken);
Process the response¶
ProcessResponse checks that the response matches the request, including the nonce.
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync(cancellationToken);
throw new CryptographicException($"The timestamp authority returned {(int)response.StatusCode} {response.StatusCode}: {error}");
}
if (response.Content.Headers.ContentType?.MediaType != "application/timestamp-reply")
{
throw new CryptographicException("The timestamp authority's reply was not a timestamp reply.");
}
var reply = await response.Content.ReadAsByteArrayAsync(cancellationToken);
var token = request.ProcessResponse(reply, out _);
Add the token to the unsigned attributes¶
The token covers the signature, not the content, so it goes in the unsigned attributes.
var timestampTokenOid = new Oid("1.2.840.113549.1.9.16.2.14");
signerInfo.AddUnsignedAttribute(new AsnEncodedData(timestampTokenOid, token.AsSignedCms().Encode()));
Verifying¶
Decode the signature¶
For a detached signature, create the SignedCms with the original content and then decode the signature. For an attached signature, decode the signature on its own.
var signedCms = detachedContent is null
? new SignedCms()
: new SignedCms(new ContentInfo(detachedContent), detached: true);
signedCms.Decode(signature);
Check the signature and the certificate¶
CheckSignature(false) checks the signature and validates each signer's certificate chain. Passing true would check the signature only.
signedCms.CheckSignature(verifySignatureOnly: false);
if (signedCms.SignerInfos.Count == 0)
{
throw new CryptographicException("The signature has no signer information.");
}
Check the RFC 3161 timestamp¶
For each signer, decode the timestamp token, confirm it was issued for this signature, and check that the time falls inside the signer certificate's validity period.
foreach (var signerInfo in signedCms.SignerInfos)
{
var certificate = signerInfo.Certificate
?? throw new CryptographicException("The signer's certificate is not in the signature.");
if (CheckTimestamp(signerInfo, certificate.NotBefore, certificate.NotAfter) == false)
{
throw new CryptographicException("The RFC 3161 timestamp is not valid.");
}
}
CheckTimestamp returns true when every timestamp is valid, false when one is not, and null when there is no timestamp.
static bool? CheckTimestamp(SignerInfo signerInfo, DateTimeOffset notBefore, DateTimeOffset notAfter)
{
var found = false;
foreach (var attribute in signerInfo.UnsignedAttributes)
{
if (attribute.Oid.Value != TimestampTokenOid.Value)
{
continue;
}
foreach (var value in attribute.Values)
{
var data = value.RawData;
if (!Rfc3161TimestampToken.TryDecode(data, out var token, out var bytesRead) || bytesRead != data.Length)
{
return false;
}
// The token must have been issued for this signer's signature value.
if (!token.VerifySignatureForSignerInfo(signerInfo, out _))
{
return false;
}
// The trusted time must fall inside the signer certificate's validity period.
var timestamp = token.TokenInfo.Timestamp;
if (timestamp < notBefore || timestamp > notAfter)
{
return false;
}
// This example requires the authority's certificate inside the token.
if (token.AsSignedCms().SignerInfos[0].Certificate is null)
{
return false;
}
found = true;
}
}
return found ? true : null;
}
Putting it all together¶
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
public static class TimestampedSignature
{
private static readonly Oid TimestampTokenOid = new("1.2.840.113549.1.9.16.2.14");
public static async Task<byte[]> SignAsync(
HttpClient httpClient,
byte[] content,
bool detached,
X509Certificate2 certificate,
Uri timestampAuthority,
CancellationToken cancellationToken)
{
var cms = new SignedCms(new ContentInfo(content), detached);
var signer = new CmsSigner(certificate) { IncludeOption = X509IncludeOption.WholeChain };
signer.SignedAttributes.Add(new Pkcs9SigningTime());
cms.ComputeSignature(signer, silent: false);
var signerInfo = cms.SignerInfos[0];
var request = Rfc3161TimestampRequest.CreateFromSignerInfo(
signerInfo,
HashAlgorithmName.SHA384,
requestSignerCertificates: true,
nonce: RandomNumberGenerator.GetBytes(8));
using var body = new ReadOnlyMemoryContent(request.Encode());
body.Headers.ContentType = new MediaTypeHeaderValue("application/timestamp-query");
using var response = await httpClient.PostAsync(timestampAuthority, body, cancellationToken);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync(cancellationToken);
throw new CryptographicException($"The timestamp authority returned {(int)response.StatusCode} {response.StatusCode}: {error}");
}
if (response.Content.Headers.ContentType?.MediaType != "application/timestamp-reply")
{
throw new CryptographicException("The timestamp authority's reply was not a timestamp reply.");
}
var reply = await response.Content.ReadAsByteArrayAsync(cancellationToken);
var token = request.ProcessResponse(reply, out _);
// The token covers the signature rather than the content, so it is an unsigned attribute.
signerInfo.AddUnsignedAttribute(new AsnEncodedData(TimestampTokenOid, token.AsSignedCms().Encode()));
return cms.Encode();
}
public static void Verify(byte[] signature, byte[]? detachedContent)
{
var signedCms = detachedContent is null
? new SignedCms()
: new SignedCms(new ContentInfo(detachedContent), detached: true);
signedCms.Decode(signature);
// false validates each signer's certificate chain as well as the signature.
signedCms.CheckSignature(verifySignatureOnly: false);
if (signedCms.SignerInfos.Count == 0)
{
throw new CryptographicException("The signature has no signer information.");
}
foreach (var signerInfo in signedCms.SignerInfos)
{
var certificate = signerInfo.Certificate
?? throw new CryptographicException("The signer's certificate is not in the signature.");
if (CheckTimestamp(signerInfo, certificate.NotBefore, certificate.NotAfter) == false)
{
throw new CryptographicException("The RFC 3161 timestamp is not valid.");
}
}
}
internal static bool? CheckTimestamp(SignerInfo signerInfo, DateTimeOffset notBefore, DateTimeOffset notAfter)
{
var found = false;
foreach (var attribute in signerInfo.UnsignedAttributes)
{
if (attribute.Oid.Value != TimestampTokenOid.Value)
{
continue;
}
foreach (var value in attribute.Values)
{
var data = value.RawData;
if (!Rfc3161TimestampToken.TryDecode(data, out var token, out var bytesRead) || bytesRead != data.Length)
{
return false;
}
if (!token.VerifySignatureForSignerInfo(signerInfo, out _))
{
return false;
}
var timestamp = token.TokenInfo.Timestamp;
if (timestamp < notBefore || timestamp > notAfter)
{
return false;
}
if (token.AsSignedCms().SignerInfos[0].Certificate is null)
{
return false;
}
found = true;
}
}
return found ? true : null;
}
}