Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- """Extract an embedded PDF signature into a separate .sig file.
- Produces two files:
- <name>.pdf – the signed byte ranges (valid PDF, signature removed)
- <name>.pdf.sig – the PKCS#7 detached signature (DER format)
- Usage:
- python3 pdf_detach_sig.py input.pdf [output_base]
- If output_base is omitted, a timestamp suffix (_YYYYMMDDhhmmss) is appended to
- the input stem to avoid overwriting the original file.
- """
- import re
- import sys
- from datetime import datetime
- from pathlib import Path
- class PDFSignatureError(ValueError):
- """Raised when signature extraction fails."""
- def find_byte_range(data: bytes) -> tuple[int, int, int, int]:
- """Return the four ByteRange integers from the signature dictionary."""
- match = re.search(rb'/ByteRange\s*\[\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*\]', data)
- if not match:
- raise PDFSignatureError("No /ByteRange found – this PDF has no embedded signature.")
- return tuple(int(v) for v in match.groups())
- def extract_signature(data: bytes, br: tuple[int, int, int, int]) -> bytes:
- """Extract the hex-encoded PKCS#7 signature and return raw DER bytes."""
- sig_offset = br[0] + br[1] # start of signature hex
- sig_end = br[2] # end of signature hex
- # The hex content is between < and > delimiters
- chunk = data[sig_offset:sig_end]
- hex_match = re.search(rb'<([0-9a-fA-F]+)', chunk)
- if not hex_match:
- raise PDFSignatureError("Could not locate hex signature data.")
- hex_str = hex_match.group(1)
- # Strip trailing zero-padding
- hex_str = hex_str.rstrip(b'0')
- if len(hex_str) % 2:
- hex_str += b'0'
- return bytes.fromhex(hex_str.decode('ascii'))
- def build_signed_content(data: bytes, br: tuple[int, int, int, int]) -> bytes:
- """Concatenate the two signed byte ranges."""
- part1 = data[br[0]:br[0] + br[1]]
- part2 = data[br[2]:br[2] + br[3]]
- return part1 + part2
- def default_output_base(input_path: Path) -> Path:
- """Derive output base by appending a timestamp suffix to the input stem."""
- suffix = datetime.now().strftime('_%Y%m%d%H%M%S')
- return input_path.parent / (input_path.stem + suffix)
- def main():
- if len(sys.argv) < 2:
- sys.exit(f"Usage: {sys.argv[0]} <input.pdf> [output_base]")
- input_path = Path(sys.argv[1])
- if not input_path.is_file():
- print(f"Error: {input_path} not found.", file=sys.stderr)
- sys.exit(1)
- if len(sys.argv) >= 3:
- out_base = Path(sys.argv[2])
- else:
- out_base = default_output_base(input_path)
- pdf_out = out_base.with_suffix('.pdf')
- sig_out = Path(str(pdf_out) + '.sig')
- data = input_path.read_bytes()
- br = find_byte_range(data)
- signed_content = build_signed_content(data, br)
- sig_der = extract_signature(data, br)
- pdf_out.write_bytes(signed_content)
- sig_out.write_bytes(sig_der)
- print(f" PDF: {pdf_out} ({len(signed_content)} bytes)")
- print(f" Sig: {sig_out} ({len(sig_der)} bytes)")
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment