Examples
All the examples follow the same procedure: they compute the document’s SHA-256 hash, send a request with a random
nonce that asks for the service’s certificate, check that the response is for that hash and nonce, print the time
and the serial number of the time stamp and save the response with the document. The address, the user name and the
password are on the Integration tab of your service’s page; the examples use the test address. They read the user
name and the password from the environment variables TSA_USER and TSA_PASSWORD.
Read the password from a secret in your environment (an environment variable, a secret store), not from the code.
Java 25, the Bouncy Castle library 1.87 (org.bouncycastle:bcpkix-jdk18on):
import java.math.BigInteger;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.security.MessageDigest;import java.security.SecureRandom;import java.util.Base64;import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;import org.bouncycastle.tsp.TimeStampRequest;import org.bouncycastle.tsp.TimeStampRequestGenerator;import org.bouncycastle.tsp.TimeStampResponse;import org.bouncycastle.tsp.TimeStampToken;
public class TimeStampExample { public static void main(String[] args) throws Exception { String userName = System.getenv("TSA_USER"); String password = System.getenv("TSA_PASSWORD");
byte[] hash = MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(Path.of("document.pdf"))); TimeStampRequestGenerator generator = new TimeStampRequestGenerator(); generator.setCertReq(true); TimeStampRequest request = generator.generate(NISTObjectIdentifiers.id_sha256, hash, new BigInteger(63, new SecureRandom()));
String basic = Base64.getEncoder().encodeToString((userName + ":" + password).getBytes(StandardCharsets.UTF_8)); HttpRequest http = HttpRequest.newBuilder(URI.create("https://tsa.test.certilia.com/qts")) .header("Content-Type", "application/timestamp-query") .header("Authorization", "Basic " + basic) .POST(HttpRequest.BodyPublishers.ofByteArray(request.getEncoded())) .build(); HttpResponse<byte[]> answer = HttpClient.newHttpClient().send(http, HttpResponse.BodyHandlers.ofByteArray()); if (answer.statusCode() != 200) throw new IllegalStateException("TSA: HTTP " + answer.statusCode());
TimeStampResponse response = new TimeStampResponse(answer.body()); // Throws TSPException if the response is not for this hash and nonce. response.validate(request); TimeStampToken token = response.getTimeStampToken(); if (token == null) throw new IllegalStateException("TSA: " + response.getStatusString()); System.out.println(token.getTimeStampInfo().getGenTime() + " " + token.getTimeStampInfo().getSerialNumber().toString(16)); Files.write(Path.of("document.pdf.tsr"), response.getEncoded()); }}.NET 10, the System.Security.Cryptography.Pkcs 10.0 package (NuGet):
using System.Net.Http.Headers;using System.Security.Cryptography;using System.Security.Cryptography.Pkcs;using System.Text;
string userName = Environment.GetEnvironmentVariable("TSA_USER")!;string password = Environment.GetEnvironmentVariable("TSA_PASSWORD")!;
byte[] hash = SHA256.HashData(await File.ReadAllBytesAsync("document.pdf"));byte[] nonce = RandomNumberGenerator.GetBytes(8);nonce[0] &= 0x7F; // a positive numberRfc3161TimestampRequest request = Rfc3161TimestampRequest.CreateFromHash( hash, HashAlgorithmName.SHA256, nonce: nonce, requestSignerCertificates: true);
using var http = new HttpClient();http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{userName}:{password}")));var content = new ByteArrayContent(request.Encode());content.Headers.ContentType = new MediaTypeHeaderValue("application/timestamp-query");HttpResponseMessage answer = await http.PostAsync("https://tsa.test.certilia.com/qts", content);answer.EnsureSuccessStatusCode();byte[] reply = await answer.Content.ReadAsByteArrayAsync();
// Checks the status, hash and nonce; throws CryptographicException if no time stamp was issued.Rfc3161TimestampToken token = request.ProcessResponse(reply, out _);Console.WriteLine($"{token.TokenInfo.Timestamp:u} {Convert.ToHexString(token.TokenInfo.GetSerialNumber().Span)}");await File.WriteAllBytesAsync("document.pdf.tsr", reply);Python 3.15, the requests 2.34 and asn1crypto 1.5 packages:
import hashlibimport osimport secrets
import requestsfrom asn1crypto import algos, tsp
user_name = os.environ["TSA_USER"]password = os.environ["TSA_PASSWORD"]
with open("document.pdf", "rb") as document: digest = hashlib.sha256(document.read()).digest()nonce = secrets.randbits(63)request = tsp.TimeStampReq({ "version": 1, "message_imprint": { "hash_algorithm": algos.DigestAlgorithm({"algorithm": "sha256"}), "hashed_message": digest, }, "nonce": nonce, "cert_req": True,})
answer = requests.post( "https://tsa.test.certilia.com/qts", data=request.dump(), headers={"Content-Type": "application/timestamp-query"}, auth=(user_name, password), timeout=30,)answer.raise_for_status()
reply = tsp.TimeStampResp.load(answer.content)status = reply["status"]["status"].nativeif status not in ("granted", "granted_with_mods"): raise RuntimeError(f"TSA: {status}")info = reply["time_stamp_token"]["content"]["encap_content_info"]["content"].parsedif info["message_imprint"]["hashed_message"].native != digest or info["nonce"].native != nonce: raise RuntimeError("TSA: the response is not for this request")print(info["gen_time"].native, format(info["serial_number"].native, "x"))with open("document.pdf.tsr", "wb") as stamp: stamp.write(answer.content)Node.js 26, the pkijs 4 and asn1js 4 packages (ES modules):
import { createHash, randomBytes } from "node:crypto";import { readFile, writeFile } from "node:fs/promises";import * as asn1js from "asn1js";import * as pkijs from "pkijs";
const userName = process.env.TSA_USER;const password = process.env.TSA_PASSWORD;
const hash = createHash("sha256").update(await readFile("document.pdf")).digest();const nonce = randomBytes(8);nonce[0] &= 0x7f; // a positive numberconst request = new pkijs.TimeStampReq({ version: 1, messageImprint: new pkijs.MessageImprint({ hashAlgorithm: new pkijs.AlgorithmIdentifier({ algorithmId: "2.16.840.1.101.3.4.2.1" }), // SHA-256 hashedMessage: new asn1js.OctetString({ valueHex: hash }), }), nonce: new asn1js.Integer({ valueHex: nonce }), certReq: true,});
const answer = await fetch("https://tsa.test.certilia.com/qts", { method: "POST", headers: { "Content-Type": "application/timestamp-query", Authorization: `Basic ${Buffer.from(`${userName}:${password}`).toString("base64")}`, }, body: Buffer.from(request.toSchema().toBER()),});if (!answer.ok) throw new Error(`TSA: HTTP ${answer.status}`);const reply = Buffer.from(await answer.arrayBuffer());
const response = pkijs.TimeStampResp.fromBER(reply);const status = response.status.status;if (status !== pkijs.PKIStatus.granted && status !== pkijs.PKIStatus.grantedWithMods) throw new Error(`TSA: ${pkijs.PKIStatus[status]}`);const signedData = new pkijs.SignedData({ schema: response.timeStampToken.content });const info = pkijs.TSTInfo.fromBER(signedData.encapContentInfo.eContent.getValue());if (!Buffer.from(info.messageImprint.hashedMessage.getValue()).equals(hash) || info.nonce?.toBigInt() !== BigInt(`0x${nonce.toString("hex")}`)) { throw new Error("TSA: the response is not for this request");}console.log(info.genTime.toISOString(), info.serialNumber.toBigInt().toString(16));await writeFile("document.pdf.tsr", reply);PHP 8.5 with the curl extension; the openssl program creates the request and reads the response (as in the
quick start):
<?php$userName = getenv('TSA_USER');$password = getenv('TSA_PASSWORD');
exec('openssl ts -query -data document.pdf -sha256 -cert -out request.tsq', $output, $code);if ($code !== 0) { throw new RuntimeException('openssl ts -query failed');}
$curl = curl_init('https://tsa.test.certilia.com/qts');curl_setopt_array($curl, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => file_get_contents('request.tsq'), CURLOPT_HTTPHEADER => ['Content-Type: application/timestamp-query'], CURLOPT_USERPWD => "$userName:$password", CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30,]);$reply = curl_exec($curl);$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);if ($reply === false || $status !== 200) { throw new RuntimeException("TSA: HTTP $status");}file_put_contents('document.pdf.tsr', $reply);
$sent = shell_exec('openssl ts -query -in request.tsq -text');$got = shell_exec('openssl ts -reply -in document.pdf.tsr -text');if (!str_contains($got, 'Status: Granted.')) { throw new RuntimeException("TSA: no time stamp issued\n$got");}preg_match('/Nonce: (\S+)/', $sent, $sentNonce);preg_match('/Nonce: (\S+)/', $got, $gotNonce);if (($sentNonce[1] ?? 'x') !== ($gotNonce[1] ?? 'y')) { throw new RuntimeException('TSA: the response is not for this request');}preg_match('/Time stamp: (.+)/', $got, $time);preg_match('/Serial number: (\S+)/', $got, $serial);echo trim($time[1]), ' ', $serial[1], PHP_EOL;Go 1.27, the github.com/digitorus/timestamp package:
package main
import ( "bytes" "crypto" "crypto/rand" "crypto/sha256" "fmt" "io" "math/big" "net/http" "os" "time"
"github.com/digitorus/timestamp")
func main() { document, err := os.ReadFile("document.pdf") check(err) hash := sha256.Sum256(document) nonce, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 63)) check(err) request, err := (×tamp.Request{HashAlgorithm: crypto.SHA256, HashedMessage: hash[:], Certificates: true, Nonce: nonce}).Marshal() check(err)
httpRequest, err := http.NewRequest(http.MethodPost, "https://tsa.test.certilia.com/qts", bytes.NewReader(request)) check(err) httpRequest.Header.Set("Content-Type", "application/timestamp-query") httpRequest.SetBasicAuth(os.Getenv("TSA_USER"), os.Getenv("TSA_PASSWORD")) answer, err := (&http.Client{Timeout: 30 * time.Second}).Do(httpRequest) check(err) defer answer.Body.Close() if answer.StatusCode != http.StatusOK { panic(fmt.Sprintf("TSA: HTTP %d", answer.StatusCode)) } reply, err := io.ReadAll(answer.Body) check(err)
// ParseResponse checks the status and the signature of the time stamp; the hash and nonce are checked here. stamp, err := timestamp.ParseResponse(reply) check(err) if !bytes.Equal(stamp.HashedMessage, hash[:]) || stamp.Nonce == nil || stamp.Nonce.Cmp(nonce) != 0 { panic("TSA: the response is not for this request") } fmt.Println(stamp.Time.UTC().Format(time.RFC3339), stamp.SerialNumber.Text(16)) check(os.WriteFile("document.pdf.tsr", reply, 0o644))}
func check(err error) { if err != nil { panic(err) }}The Go example also checks the time stamp’s signature with the certificate in the time stamp; the other examples do not check the signature. None of them checks the chain to AKD’s root certificate; this requires the certificate chain of AKD’s time-stamping service (see Archives and re-stamping).
Adobe Acrobat Reader
Section titled “Adobe Acrobat Reader”For time stamps on signatures in Adobe Acrobat Reader, add a new time-stamp server in its settings (Edit → Preferences → Signatures → Document Timestamping → More… → Time Stamp Servers → New). Enter a name (e.g. Certilia), the service’s address, the user name and the password, then set it as the default (Set Default).