Primjeri
Svi primjeri izvode isti postupak: izračunavaju SHA-256 dokumenta, šalju zahtjev s nasumičnim nonce-om i traženim
certifikatom usluge, provjeravaju da je odgovor za taj hash i nonce, ispisuju vrijeme i serijski broj žiga i spremaju
odgovor uz dokument. Adresa, korisničko ime i lozinka nalaze se na kartici Integracija na stranici vaše usluge;
primjeri koriste testnu adresu.
Korisničko ime i lozinku čitaju iz varijabli okoline TSA_USER i TSA_PASSWORD.
Lozinku čitajte iz tajne vaše okoline (varijabla okoline, trezor tajni), ne iz koda.
Java 25, biblioteka Bouncy Castle 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 Zig { 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("dokument.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()); // Baca TSPException ako odgovor nije za ovaj hash i 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("dokument.pdf.tsr"), response.getEncoded()); }}.NET 10, paket System.Security.Cryptography.Pkcs 10.0 (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("dokument.pdf"));byte[] nonce = RandomNumberGenerator.GetBytes(8);nonce[0] &= 0x7F; // pozitivan brojRfc3161TimestampRequest 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();
// Provjerava status, hash i nonce; baca CryptographicException ako žig nije izdan.Rfc3161TimestampToken token = request.ProcessResponse(reply, out _);Console.WriteLine($"{token.TokenInfo.Timestamp:u} {Convert.ToHexString(token.TokenInfo.GetSerialNumber().Span)}");await File.WriteAllBytesAsync("dokument.pdf.tsr", reply);Python 3.15, paketi requests 2.34 i asn1crypto 1.5:
import hashlibimport osimport secrets
import requestsfrom asn1crypto import algos, tsp
user_name = os.environ["TSA_USER"]password = os.environ["TSA_PASSWORD"]
with open("dokument.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: odgovor nije za ovaj zahtjev")print(info["gen_time"].native, format(info["serial_number"].native, "x"))with open("dokument.pdf.tsr", "wb") as stamp: stamp.write(answer.content)Node.js 26, paketi pkijs 4 i asn1js 4 (ES moduli):
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("dokument.pdf")).digest();const nonce = randomBytes(8);nonce[0] &= 0x7f; // pozitivan brojconst 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: odgovor nije za ovaj zahtjev");}console.log(info.genTime.toISOString(), info.serialNumber.toBigInt().toString(16));await writeFile("dokument.pdf.tsr", reply);PHP 8.5 s ekstenzijom curl; zahtjev izrađuje i odgovor čita program openssl (kao u
brzom početku):
<?php$userName = getenv('TSA_USER');$password = getenv('TSA_PASSWORD');
exec('openssl ts -query -data dokument.pdf -sha256 -cert -out zahtjev.tsq', $output, $code);if ($code !== 0) { throw new RuntimeException('openssl ts -query nije uspio');}
$curl = curl_init('https://tsa.test.certilia.com/qts');curl_setopt_array($curl, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => file_get_contents('zahtjev.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('dokument.pdf.tsr', $reply);
$sent = shell_exec('openssl ts -query -in zahtjev.tsq -text');$got = shell_exec('openssl ts -reply -in dokument.pdf.tsr -text');if (!str_contains($got, 'Status: Granted.')) { throw new RuntimeException("TSA: žig nije izdan\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: odgovor nije za ovaj zahtjev');}preg_match('/Time stamp: (.+)/', $got, $time);preg_match('/Serial number: (\S+)/', $got, $serial);echo trim($time[1]), ' ', $serial[1], PHP_EOL;Go 1.27, paket github.com/digitorus/timestamp:
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("dokument.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 provjerava status i potpis žiga; hash i nonce provjeravamo ovdje. stamp, err := timestamp.ParseResponse(reply) check(err) if !bytes.Equal(stamp.HashedMessage, hash[:]) || stamp.Nonce == nil || stamp.Nonce.Cmp(nonce) != 0 { panic("TSA: odgovor nije za ovaj zahtjev") } fmt.Println(stamp.Time.UTC().Format(time.RFC3339), stamp.SerialNumber.Text(16)) check(os.WriteFile("dokument.pdf.tsr", reply, 0o644))}
func check(err error) { if err != nil { panic(err) }}Go primjer provjerava i potpis žiga certifikatom koji je u žigu; ostali primjeri potpis ne provjeravaju. Nijedan ne provjerava lanac do AKD-ova korijenskog certifikata; za to je potreban lanac certifikata AKD-ove usluge vremenskih žigova (vidi Arhiva i ponovna ugradnja žiga).
Adobe Acrobat Reader
Odjeljak „Adobe Acrobat Reader”Za vremenske žigove na potpisima u Adobe Acrobat Readeru u postavkama poslužitelja vremenskih žigova dodajte novi poslužitelj (izbornici na engleskom: Edit → Preferences → Signatures → Document Timestamping → More… → Time Stamp Servers → New). Upišite naziv (npr. Certilia), adresu usluge, korisničko ime i lozinku te ga postavite kao zadani (Set Default).