Last active
February 23, 2025 20:53
-
-
Save liucoj/3fe7dfcbe1d4a751a8a3a872f53dd02c to your computer and use it in GitHub Desktop.
Decode .p7m files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| import sys | |
| from cryptography.hazmat.primitives import serialization | |
| from cryptography.hazmat.primitives.asymmetric import padding | |
| from cryptography.hazmat.primitives import hashes | |
| from asn1crypto import pem, cms | |
| def decode_p7m_to_pdf(p7m_file_path, output_pdf_path): | |
| # Load the .p7m file | |
| with open(p7m_file_path, 'rb') as p7m_file: | |
| p7m_data = p7m_file.read() | |
| # Parse the PKCS#7 data | |
| p7m = cms.ContentInfo.load(p7m_data) | |
| # Extract the content (assuming it's a PDF) | |
| if p7m['content_type'].native == 'signed_data': | |
| signed_data = p7m['content'] | |
| encap_content_info = signed_data['encap_content_info'] | |
| pdf_data = encap_content_info['content'].native | |
| elif p7m['content_type'].native == 'enveloped_data': | |
| enveloped_data = p7m['content'] | |
| encrypted_content_info = enveloped_data['encrypted_content_info'] | |
| pdf_data = encrypted_content_info['content'].native | |
| else: | |
| raise ValueError("Unsupported PKCS#7 content type") | |
| # Write the PDF data to the output file | |
| with open(output_pdf_path, 'wb') as pdf_file: | |
| pdf_file.write(pdf_data) | |
| print(f"Decoded {p7m_file_path} to {output_pdf_path}") | |
| def decode_folder(input_folder, output_folder): | |
| if not os.path.exists(output_folder): | |
| os.makedirs(output_folder) | |
| for filename in os.listdir(input_folder): | |
| if filename.endswith('.p7m'): | |
| input_p7m_file = os.path.join(input_folder, filename) | |
| # Remove the .p7m extension and add .pdf extension | |
| output_pdf_file = os.path.join(output_folder, os.path.splitext(filename)[0] + '.pdf') | |
| decode_p7m_to_pdf(input_p7m_file, output_pdf_file) | |
| if __name__ == "__main__": | |
| if len(sys.argv) != 3: | |
| print("Usage: python decode_p7m_folder.py <input_folder> <output_folder>") | |
| sys.exit(1) | |
| input_folder = sys.argv[1] | |
| output_folder = sys.argv[2] | |
| if not os.path.isdir(input_folder): | |
| print(f"Error: {input_folder} is not a valid directory.") | |
| sys.exit(1) | |
| decode_folder(input_folder, output_folder) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python script to decode .P7M files