Category: Digital Signatures
Complexity: ⭐⭐⭐ (Medium)
Prerequisites: Signature available, TSA access
Estimated Time: 10-15 Minutes
This scenario describes adding timestamps to digital signatures (RFC 3161). Timestamps prove that a signature existed at a specific point in time and enable:
Concept:
using WvdS.Security.Cryptography.X509Certificates.Extensions.PQ; using System.Security.Cryptography; using System.Security.Cryptography.Pkcs; using var ctx = PqCryptoContext.Initialize(); // Load signature var signature = File.ReadAllBytes("document.sig"); // Calculate hash of signature var signatureHash = SHA256.HashData(signature); // Create timestamp request (RFC 3161) var tsRequest = new Rfc3161TimestampRequest( messageHash: signatureHash, hashAlgorithm: HashAlgorithmName.SHA256, requestedPolicyId: null, // Default Policy nonce: GenerateNonce(), requestSignerCertificates: true ); // Send request to TSA using var http = new HttpClient(); var content = new ByteArrayContent(tsRequest.Encode()); content.Headers.ContentType = new MediaTypeHeaderValue("application/timestamp-query"); var response = await http.PostAsync("http://timestamp.digicert.com", content); var tsResponseBytes = await response.Content.ReadAsByteArrayAsync(); // Parse response var tsResponse = Rfc3161TimestampToken.Decode(tsResponseBytes, out int bytesConsumed); // Validate if (!tsResponse.VerifySignatureForHash(signatureHash, HashAlgorithmName.SHA256, out var signerCert, null)) { throw new CryptographicException("Timestamp signature invalid"); } // Save token File.WriteAllBytes("document.sig.tst", tsResponse.AsSignedCms().Encode()); Console.WriteLine("Timestamp received:"); Console.WriteLine($" Time: {tsResponse.TokenInfo.Timestamp}"); Console.WriteLine($" TSA: {signerCert.Subject}"); Console.WriteLine($" Policy: {tsResponse.TokenInfo.PolicyId}");
public class TimestampService { private readonly string _tsaUrl; private readonly HttpClient _http; public TimestampService(string tsaUrl) { _tsaUrl = tsaUrl; _http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; } public async Task<SignedCms> AddTimestamp(SignedCms signedCms) { foreach (var signerInfo in signedCms.SignerInfos) { // Signature hash for timestamp var signatureHash = SHA256.HashData(signerInfo.GetSignature()); // Timestamp request var tsRequest = new Rfc3161TimestampRequest( signatureHash, HashAlgorithmName.SHA256, requestedPolicyId: null, nonce: GenerateNonce(), requestSignerCertificates: true ); // Send to TSA var content = new ByteArrayContent(tsRequest.Encode()); content.Headers.ContentType = new MediaTypeHeaderValue("application/timestamp-query"); var response = await _http.PostAsync(_tsaUrl, content); response.EnsureSuccessStatusCode(); var tsResponseBytes = await response.Content.ReadAsByteArrayAsync(); var tsToken = Rfc3161TimestampToken.Decode(tsResponseBytes, out _); // Add as unsigned attribute var timestampAttr = new AsnEncodedData( new Oid("1.2.840.113549.1.9.16.2.14"), // id-aa-timeStampToken tsToken.AsSignedCms().Encode() ); signerInfo.AddUnsignedAttribute(timestampAttr); } return signedCms; } private byte[] GenerateNonce() { var nonce = new byte[8]; RandomNumberGenerator.Fill(nonce); return nonce; } }
public class TimestampValidator { public TimestampValidationResult Validate( byte[] timestampToken, byte[] originalSignature, X509Certificate2Collection? trustedTsaCerts = null) { var result = new TimestampValidationResult(); try { var tsToken = Rfc3161TimestampToken.Decode(timestampToken, out _); result.Timestamp = tsToken.TokenInfo.Timestamp; result.PolicyId = tsToken.TokenInfo.PolicyId?.Value; // Verify hash var expectedHash = SHA256.HashData(originalSignature); if (!tsToken.TokenInfo.GetMessageHash().ReadOnlySpan.SequenceEqual(expectedHash)) { result.IsValid = false; result.Error = "Hash does not match"; return result; } // Verify signature if (!tsToken.VerifySignatureForHash(expectedHash, HashAlgorithmName.SHA256, out var tsaCert, trustedTsaCerts)) { result.IsValid = false; result.Error = "TSA signature invalid"; return result; } result.TsaCertificate = tsaCert; // Validate TSA certificate chain var chain = new X509Chain(); chain.ChainPolicy.RevocationMode = X509RevocationMode.Online; if (trustedTsaCerts != null) { chain.ChainPolicy.CustomTrustStore.AddRange(trustedTsaCerts); chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; } result.IsValid = chain.Build(tsaCert); if (!result.IsValid) { result.Error = "TSA certificate chain invalid"; } } catch (Exception ex) { result.IsValid = false; result.Error = ex.Message; } return result; } } public class TimestampValidationResult { public bool IsValid { get; set; } public DateTimeOffset? Timestamp { get; set; } public string? PolicyId { get; set; } public X509Certificate2? TsaCertificate { get; set; } public string? Error { get; set; } }
| Provider | URL | Qualified (eIDAS) |
|---|---|---|
| DigiCert | http://timestamp.digicert.com | No |
| Sectigo | http://timestamp.sectigo.com | No |
| GlobalSign | http://timestamp.globalsign.com | No |
| D-TRUST | http://zeitstempel.2.1.3.bundesdruckerei.de | Yes |
| SwissSign | http://tsa.swisscom.com/tsa | Yes |
| Bundesdruckerei | http://ts.2.bundesdruckerei.de | Yes |
eIDAS: A qualified TSA is required for qualified electronic signatures.
public class LongTermArchive { public async Task ExtendValidation( SignedCms signedCms, string tsaUrl, X509Certificate2Collection validationData) { // 1. Embed validation data (certificates, CRLs, OCSP) AddValidationData(signedCms, validationData); // 2. Add archive timestamp var timestampService = new TimestampService(tsaUrl); await timestampService.AddArchiveTimestamp(signedCms); // This process can be repeated periodically // to keep the signature validatable long-term } }
| Application | Timestamp Required? | Qualified? |
|---|---|---|
| Code Signing | Required | No |
| eIDAS QES | Required | Yes |
| PDF/A Archival | Recommended | Depending on requirements |
| S/MIME | Optional | No |
| Healthcare | Required | Depending on country |
| Relationship | Scenario | Description |
|---|---|---|
| Prerequisite | 8.1 Sign Document | Create signature |
| Prerequisite | 8.2 Sign Code | Code signature |
| Next Step | 8.4 Verify Signature | Validation |
« ← 8.2 Sign Code | ↑ Signatures Overview | 8.4 Verify Signature → »
Wolfgang van der Stille @ EMSR DATA d.o.o. - Post-Quantum Cryptography Professional