This Python script is a utility for creating and sending...

August 29, 2025 at 02:47 PM

#!/usr/bin/env python3 import base64 import hashlib import json import argparse from datetime import datetime from typing import Any, Union, Dict import jwt import requests from cryptography.x509 import load_pem_x509_certificate from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.serialization import Encoding def minify_json(data: Union[dict, str]) -> str:   """Returns minified JSON."""   if isinstance(data, dict):     return json.dumps(data, separators=(',', ':'))   return json.dumps(json.loads(data), separators=(',', ':')) def load_file(path: str, parse_json: bool = False) -> Any:   """Loads file content as text or JSON."""   with open(path, "r") as file:     return json.load(file) if parse_json else file.read() def get_send_date() -> str:   """Generates current date in ISO 8601 format with milliseconds."""   now = datetime.utcnow()   ms = int(now\.microsecond / 1000)   return now\.strftime('%Y-%m-%dT%H:%M:%S') + f'.{ms:03d}Z' def generate_detached_jws(private_key: str, certificate: str, payload: Dict[str, Any]) -> str:   """Generates a detached JWS signature and verifies it."""   cert_obj = load_pem_x509_certificate(certificate.encode(), default_backend())   cert_der = cert_obj.public_bytes(encoding=Encoding.DER)   thumbprint = hashlib.sha256(cert_der).digest()   x5t_s256 = base64.urlsafe_b64encode(thumbprint).decode().rstrip("=")   algorithm = "RS256"   headers = {"alg": algorithm, "x5t#S256": x5t_s256, "typ": "JWT"}   attached_jws = jwt.encode(payload=payload, key=private_key, algorithm=algorithm, headers=headers)   try:     header, _, signature = attached_jws.split(".")   except ValueError as e:     raise ValueError("Generated JWS has wrong format.") from e   public_key = cert_obj.public_key()   jwt.decode(attached_jws, public_key, algorithms=[algorithm])   return f"{header}..{signature}" def send_request(url: str, payload: Dict[str, Any], detached_jws: str, request_id: str) -> None:   """Sends a POST request with minified payload and appropriate headers."""   headers = {     "Accept-Encoding": "gzip",     "Accept-Language": "pl",     "x-jws-signature": detached_jws,     "x-request-id": request_id,     "Content-Type": "application/json"   }   response = requests.post(url, data=minify_json(payload), headers=headers)   print("Response status code:", response.status_code)   if response.status_code != 204:     print("Response body:", response.text) def main():   parser = argparse.ArgumentParser(description="JWT signing script")   parser.add_argument("--key", required=True, help="Private PEM key file path")   parser.add_argument("--cert", required=True, help="Public PEM certificate file path")   parser.add_argument("--payload", required=True, help="JSON file path to sign")   parser.add_argument("--url", required=True, help="API URL")   args = parser.parse_args()   private_key = load_file(args.key)   certificate = load_file(args.cert)   payload = load_file(args.payload, parse_json=True)   payload['requestHeader']['sendDate'] = get_send_date()   detached_jws = generate_detached_jws(private_key, certificate, payload)   print("Your signature:", detached_jws)   send_request(args.url, payload, detached_jws, payload['requestHeader']['requestId']) if **name** == "**main**":   main()

This Python script is a utility for creating and sending a detached JSON Web Signature (JWS) along with a JSON payload via a POST request to an API endpoint. Here's what the code does:

High-Level Workflow:

  1. Input Handling & Argument Parsing:

    • It uses argparse to parse command-line arguments for:
      • Private key file (--key)
      • Public certificate file (--cert)
      • JSON payload file (--payload)
      • API URL (--url).
  2. Payload Processing:

    • The provided JSON file is loaded and modified to include a sendDate timestamp in ISO 8601 format under the requestHeader section.
  3. JWS Signature Generation:

    • Reads the X.509 certificate and private key.
    • Computes a SHA-256 thumbprint of the certificate (base64 URL-encoded).
    • Constructs a JWS header containing the signature algorithm (RS256) and the certificate thumbprint.
    • Encodes the payload, signs it with the private key, and generates a detached JWS signature (header and signature without the payload).
    • Verifies the generated JWS against the certificate’s public key.
  4. API Request Sending:

    • Sends the JSON payload (minified) as a POST request to the specified API URL.
    • Includes the detached JWS signature (x-jws-signature) and other custom headers (x-request-id and Content-Type).
  5. Response Handling:

    • Prints the response status code.
    • If the status code is not 204 (No Content), it also prints the response body.

Key Functions Explained:

minify_json(data)

  • Converts the input JSON (dictionary or string) into a minified JSON string (removing whitespace, newlines, etc.).

load_file(path, parse_json)

  • Reads the content of a file.
  • If parse_json=True, it parses the file as JSON and returns a Python dictionary.

get_send_date()

  • Generates the current UTC time in ISO 8601 format with millisecond precision.

generate_detached_jws(private_key, certificate, payload)

  • Generates a detached JWS signature:
    • Extracts public key information from the provided certificate.
    • Computes the certificate's thumbprint.
    • Constructs a JWS header based on RS256 algorithm.
    • Signs the JSON payload with the provided private key.
    • Verifies the signature using the public key from the certificate.
    • Returns the detached JWS (header and signature).

send_request(url, payload, detached_jws, request_id)

  • Sends a HTTP POST request containing the minified JSON payload to the given API URL.
  • Sets various headers, including:
    • x-jws-signature with the detached JWS.
    • x-request-id for tracing.
  • Prints the response details.

Main Flow (main Function):

  • Loads key, certificate, and payload from files.
  • Updates the sendDate in the payload request header.
  • Generates a detached JWS for the payload.
  • Sends the payload and JWS signature to the specified API endpoint.

Use Case:

This script is useful in scenarios where secure communication and integrity verification are required, such as interacting with an API that enforces digital signatures on payloads. The detached JWS mechanism ensures the payload remains unaltered during transmission.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node