Guest User

Untitled

a guest
Mar 22nd, 2026
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.08 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. """Extract an embedded PDF signature into a separate .sig file.
  3.  
  4. Produces two files:
  5.  <name>.pdf     – the signed byte ranges (valid PDF, signature removed)
  6.  <name>.pdf.sig – the PKCS#7 detached signature (DER format)
  7.  
  8. Usage:
  9.  python3 pdf_detach_sig.py input.pdf [output_base]
  10.  
  11. If output_base is omitted, a timestamp suffix (_YYYYMMDDhhmmss) is appended to
  12. the input stem to avoid overwriting the original file.
  13. """
  14.  
  15. import re
  16. import sys
  17. from datetime import datetime
  18. from pathlib import Path
  19.  
  20.  
  21. class PDFSignatureError(ValueError):
  22.     """Raised when signature extraction fails."""
  23.  
  24.  
  25. def find_byte_range(data: bytes) -> tuple[int, int, int, int]:
  26.     """Return the four ByteRange integers from the signature dictionary."""
  27.     match = re.search(rb'/ByteRange\s*\[\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*\]', data)
  28.     if not match:
  29.         raise PDFSignatureError("No /ByteRange found – this PDF has no embedded signature.")
  30.     return tuple(int(v) for v in match.groups())
  31.  
  32.  
  33. def extract_signature(data: bytes, br: tuple[int, int, int, int]) -> bytes:
  34.     """Extract the hex-encoded PKCS#7 signature and return raw DER bytes."""
  35.     sig_offset = br[0] + br[1]  # start of signature hex
  36.     sig_end = br[2]             # end of signature hex
  37.  
  38.     # The hex content is between < and > delimiters
  39.     chunk = data[sig_offset:sig_end]
  40.     hex_match = re.search(rb'<([0-9a-fA-F]+)', chunk)
  41.     if not hex_match:
  42.         raise PDFSignatureError("Could not locate hex signature data.")
  43.     hex_str = hex_match.group(1)
  44.  
  45.     # Strip trailing zero-padding
  46.     hex_str = hex_str.rstrip(b'0')
  47.     if len(hex_str) % 2:
  48.         hex_str += b'0'
  49.  
  50.     return bytes.fromhex(hex_str.decode('ascii'))
  51.  
  52.  
  53. def build_signed_content(data: bytes, br: tuple[int, int, int, int]) -> bytes:
  54.     """Concatenate the two signed byte ranges."""
  55.     part1 = data[br[0]:br[0] + br[1]]
  56.     part2 = data[br[2]:br[2] + br[3]]
  57.     return part1 + part2
  58.  
  59.  
  60. def default_output_base(input_path: Path) -> Path:
  61.     """Derive output base by appending a timestamp suffix to the input stem."""
  62.     suffix = datetime.now().strftime('_%Y%m%d%H%M%S')
  63.     return input_path.parent / (input_path.stem + suffix)
  64.  
  65.  
  66. def main():
  67.     if len(sys.argv) < 2:
  68.         sys.exit(f"Usage: {sys.argv[0]} <input.pdf> [output_base]")
  69.  
  70.     input_path = Path(sys.argv[1])
  71.     if not input_path.is_file():
  72.         print(f"Error: {input_path} not found.", file=sys.stderr)
  73.         sys.exit(1)
  74.  
  75.     if len(sys.argv) >= 3:
  76.         out_base = Path(sys.argv[2])
  77.     else:
  78.         out_base = default_output_base(input_path)
  79.  
  80.     pdf_out = out_base.with_suffix('.pdf')
  81.     sig_out = Path(str(pdf_out) + '.sig')
  82.  
  83.     data = input_path.read_bytes()
  84.     br = find_byte_range(data)
  85.  
  86.     signed_content = build_signed_content(data, br)
  87.     sig_der = extract_signature(data, br)
  88.  
  89.     pdf_out.write_bytes(signed_content)
  90.     sig_out.write_bytes(sig_der)
  91.  
  92.     print(f"  PDF: {pdf_out} ({len(signed_content)} bytes)")
  93.     print(f"  Sig: {sig_out} ({len(sig_der)} bytes)")
  94.  
  95.  
  96. if __name__ == '__main__':
  97.     main()
  98.  
Advertisement
Add Comment
Please, Sign In to add comment