Skip to content

Instantly share code, notes, and snippets.

@liucoj
Last active February 23, 2025 20:53
Show Gist options
  • Select an option

  • Save liucoj/3fe7dfcbe1d4a751a8a3a872f53dd02c to your computer and use it in GitHub Desktop.

Select an option

Save liucoj/3fe7dfcbe1d4a751a8a3a872f53dd02c to your computer and use it in GitHub Desktop.

Revisions

  1. liucoj renamed this gist Feb 23, 2025. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. liucoj created this gist Feb 23, 2025.
    57 changes: 57 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    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)