How to Timestamp Files in Python with rfc3161ng

Qualified Timestamping in Python using rfc3161ng

Learn how to request, save, and verify qualified RFC 3161 timestamp tokens (.tsr) in Python using the rfc3161ng library.

Prerequisites & Environment:

Install the required Python library via pip:

pip install rfc3161ng

Step 1: Request and Save a Timestamp Token (.tsr)

Read the binary content of your file, compute its SHA-256 digest, send an HTTP RFC 3161 timestamp request to the TSA server, and write the returned token to disk.

import hashlib
import rfc3161ng

def request_timestamp(file_path: str, output_tsr_path: str, tsa_url: str):
    # 1. Read target file binary data
    with open(file_path, "rb") as f:
        file_data = f.read()

    # 2. Connect to TSA server and request RFC 3161 timestamp
    rt = rfc3161ng.RemoteTimestampingTest(tsa_url)
    
    # Compute SHA-256 hash and obtain timestamp response (.tsr)
    tsr_data = rt.timestamp(data=file_data, hashname="sha256")

    # 3. Save raw timestamp token to disk
    with open(output_tsr_path, "wb") as f:
        f.write(tsr_data)

    print(f"[SUCCESS] Timestamp saved to: {output_tsr_path}")

Step 2: Verify the Timestamp Token (.tsr)

Read the saved .tsr response file and validate the encoded timestamp token against the SHA-256 hash of the original file.

import hashlib
import rfc3161ng

def verify_timestamp(file_path: str, tsr_path: str) -> bool:
    # 1. Read original file and compute SHA-256 digest
    with open(file_path, "rb") as f:
        file_data = f.read()

    # 2. Read saved timestamp response token (.tsr)
    with open(tsr_path, "rb") as f:
        tsr_data = f.read()

    # 3. Check hash integrity matching
    verified, signing_time = rfc3161ng.check_timestamp(
        tsr_data,
        data=file_data,
        hashname="sha256"
    )

    if verified:
        print(f"[SUCCESS] Timestamp is valid! Signed at (UTC): {signing_time}")
        return True
    else:
        print("[ERROR] Invalid timestamp or hash mismatch.")
        return False

Execution Example

Run the entire workflow in a standalone Python script:

if __name__ == "__main__":
    file_to_sign = "document.pdf"
    tsr_output = "document.pdf.tsr"
    tsa_server_url = "https://tsaexample.com/myserver.aspx"

    # 1. Request Timestamp
    request_timestamp(file_to_sign, tsr_output, tsa_server_url)

    # 2. Verify Timestamp
    is_valid = verify_timestamp(file_to_sign, tsr_output)
    print(f"Verification Result: {is_valid}")
Why use rfc3161ng? It is an actively maintained fork of pyRFC3161 built on top of pyasn1 and cryptography, offering a clean Pythonic API to handle ASN.1 structures and binary HTTP encodings transparently.