Recursive AI

Timestamp a file with RFC 3161 in C#

OneCrypto is a free, open-source cryptography library for .NET from Recursive AI. MIT or Apache-2.0, preview, no native dependencies.

An RFC 3161 timestamp binds a file’s hash to an authority’s stated time. This example contacts the live freetsa.org service.

Terminal
dotnet add package RecursiveAI.OneCrypto --prerelease
dotnet add package RecursiveAI.OneCrypto.Online --prerelease

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

message.txt is in the download; its contents are Cookbook timestamp sample. followed by a newline.

C#
using System.Security.Cryptography;
using RecursiveAI.OneCrypto.Online;
using RecursiveAI.OneCrypto.Tsp;
 
var request = TimeStampRequest.Create(
    new TimeStampRequestOptions
    {
        Hash = HashAlgorithmName.SHA256,
        MessageImprint = SHA256.HashData(
            File.ReadAllBytes("message.txt")),
        Nonce = TimeStampRequest.NewNonce(),
        CertReq = true
    });
var tsa = new TsaClient(
    new Fetcher(new HttpTransport()),
    new Uri("https://freetsa.org/tsr"));
var response = await tsa.GetTimestampAsync(
    request, default);
File.WriteAllBytes("timestamp.tsr",
    response.ToArray());
var report = TimeStampVerifier.Verify(
    request, response);
Console.WriteLine($"Valid: {report.IsValid}");
Console.WriteLine(
    $"Trust: {report.Find("trust")!.Status}");
Text
Valid: True
Trust: NotApplicable

Valid means no verification check failed or was unsupported; authority trust is evaluated only when you supply trust anchors.

Writes timestamp.tsr, the complete response from the server.

Unzip the example, then dotnet run.

The full program

The full program adds a 40-second timeout and prints the authority’s stated time.

C#
using System.Security.Cryptography;
using RecursiveAI.OneCrypto.Online;
using RecursiveAI.OneCrypto.Tsp;
 
var request = TimeStampRequest.Create(new TimeStampRequestOptions
{
    Hash = HashAlgorithmName.SHA256,
    MessageImprint = SHA256.HashData(File.ReadAllBytes("message.txt")),
    Nonce = TimeStampRequest.NewNonce(),
    CertReq = true
});
var tsa = new TsaClient(new Fetcher(new HttpTransport()),
    new Uri("https://freetsa.org/tsr"));
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(40));
var response = await tsa.GetTimestampAsync(request, timeout.Token);
File.WriteAllBytes("timestamp.tsr", response.ToArray());
var report = TimeStampVerifier.Verify(request, response);
Console.WriteLine($"Valid: {report.IsValid}");
Console.WriteLine($"Imprint: {report.Find("message-imprint")!.Status}");
Console.WriteLine($"Nonce: {report.Find("nonce")!.Status}");
Console.WriteLine($"Trust: {report.Find("trust")!.Status}");
Console.WriteLine($"Time: {report.GenTime:yyyy-MM-dd HH:mm:ss'Z'}");

The live request printed:

Text
Valid: True
Imprint: Passed
Nonce: Passed
Trust: NotApplicable
Time: 2026-11-16 10:36:34Z

Your timestamp’s time will differ. This example uses the live freetsa.org service, so it depends on network access and the service’s availability. Its usage policy permits commercial use, sets a public-service request-rate limit, and provides the service on a best-effort basis without an SLA.

A failed network request raises an exception; a received rejection or invalid token must not be treated as a successful timestamp just because its bytes were saved.

Variations

For offline tests, replace Program.cs with this local-authority example. tsa.der is CN=Cookbook test TSA, issued by CN=Cookbook test root, valid from May 31 through June 30, 2026. The included test-key.pem starts with -----BEGIN PRIVATE KEY----- and is public demonstration material, never a production credential. The time is supplied by the test, not an independent service.

C#
using System.Security.Cryptography;
using RecursiveAI.OneCrypto;
using RecursiveAI.OneCrypto.Tsp;
using RecursiveAI.OneCrypto.X509;
 
using var key = ECDsa.Create();
key.ImportFromPem(File.ReadAllText("test-key.pem"));
var certificate = Certificate.Parse(File.ReadAllBytes("tsa.der").AsMemory());
var authority = new TimeStampAuthority(new TimeStampAuthorityOptions
{
    Certificate = certificate,
    Signer = X509Signer.FromECDsa(key),
    DefaultPolicy = "1.3.6.1.4.1.55555.1"
}, new CounterTimeStampSerialSource(1));
var request = TimeStampRequest.Create(new TimeStampRequestOptions
{
    Hash = HashAlgorithmName.SHA256,
    MessageImprint = SHA256.HashData(File.ReadAllBytes("message.txt")),
    Nonce = TimeStampRequest.NewNonce(),
    CertReq = true
});
var time = new DateTimeOffset(2026, 6, 1, 12, 0, 0, TimeSpan.Zero);
var response = authority.Handle(request.Encoded, time);
File.WriteAllBytes("timestamp.tsr", response.Encoded.ToArray());
var report = TimeStampVerifier.Verify(request, response.Encoded);
Console.WriteLine($"Status: {response.Status}");
Console.WriteLine($"Valid: {report.IsValid}");
Console.WriteLine($"Imprint: {report.Find("message-imprint")!.Status}");
Console.WriteLine($"Nonce: {report.Find("nonce")!.Status}");
Console.WriteLine($"Trust: {report.Find("trust")!.Status}");
Text
Status: Granted
Valid: True
Imprint: Passed
Nonce: Passed
Trust: NotApplicable

The local authority has no network or clock. Its in-memory counter serial source is for this single-process test; a hosted authority is responsible for serial uniqueness across processes.

The short answer

Hash the file, create a TimeStampRequest with the digest and a fresh nonce, obtain a timestamp response, and verify the response against that same request. The file itself is not the timestamp request: RFC 3161 sends a message imprint consisting of a hash algorithm and digest. The RFC’s request definition describes that structure.

OneCrypto’s core package supplies the request, response and verifier; its online package sends the request to a server. The main recipe obtains a real response from freetsa.org. A trust decision about the authority’s certificate is separate from the token checks: the sample does not supply anchors, so it explicitly reports trust as not evaluated. The local-authority variation is only for tests.

How do you timestamp a file in C# with RFC 3161?

Use the file’s bytes as the hash input. The sample hashes message.txt with SHA-256 and stores the digest in MessageImprint. It asks for the authority’s certificate with CertReq = true, so the verifier can find the signer certificate in the response. It also creates a random nonce and keeps the request object for verification.

The online client sends the request to https://freetsa.org/tsr with GetTimestampAsync. It returns the response bytes as received, including a rejection, so the program then calls TimeStampVerifier.Verify against the original request. The online-client docs distinguish this from StampAsync, which builds and verifies a request for you. Here the explicit request makes the hash and nonce visible in the code.

The output timestamp.tsr contains the complete response, including status and the granted token. It is separate from the input file; the program does not edit or append bytes to message.txt. Keep the response with the file and retain the request when you need to check the echoed nonce later.

How do you verify an RFC 3161 timestamp in C#?

Pass the original request and received response bytes to TimeStampVerifier.Verify. The full program prints the message-imprint and nonce findings separately. A matching imprint binds the response to the digest you requested; the nonce binds it to that request rather than an earlier response for identical content. A request without a nonce cannot distinguish such a replay and gets NotApplicable for that check.

The verifier also checks the signed token, the timestamping certificate’s permitted usage, the signing-certificate attribute, the stated time against the certificate’s validity, and the cryptographic policy. These are not interchangeable with trusting the issuer. In particular, Valid: True does not establish that the authority is trusted: without anchors, trust was not evaluated at all, even though the response came from a real server.

For an authority-trust decision, pass your chosen roots in TimeStampVerifyOptions.TrustAnchors. That asks the verifier to build the TSA’s certificate path at the token’s time. A valid path with unknown revocation is reported as Warning, not plain Passed. The timestamping docs specify that offline unknown revocation is never reported as plain passed trust. Downloading a root from the same service is not an independent production trust decision.

When checking a stored file later, recompute the digest from the file you actually have. Verifying an old request against a response only proves their relationship; it does not by itself prove that today’s file still has the requested digest. Preserve the original file bytes rather than recreating a text file with a different encoding or line ending and assuming its hash will match.

All onecrypto recipes