Advertisement
mengyuxin

EncryptPDF.py

Jan 6th, 2018
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.21 KB | None | 0 0
  1. #! python3
  2. # -*- coding: utf-8 -*-
  3. #-------------------------------------------------------------------------------
  4. # EncryptPDF.py - Encrypt a PDF file to avoid changing by someone.
  5. #                 Add a random owner password to PDF file.
  6. # Created by: Meng Yuxin
  7. # Created on: 24/12/2017
  8. #-------------------------------------------------------------------------------
  9. """
  10. Reference:
  11.    http://www.python.org
  12.    https://docs.python.org/3/
  13.    http://pythonhosted.org/PyPDF2/
  14.    https://github.com/mstamy2/PyPDF2
  15.    https://github.com/mengyuxin/EncryptPDF
  16.    https://pypi.python.org/pypi/PyPDF2/1.26.0
  17.    
  18. PyPDF2 is a pure-python PDF library capable of splitting, merging together, cropping, and transforming the pages of PDF files.
  19. It can also add custom data, viewing options, and passwords to PDF files.
  20. It can retrieve text and metadata from PDFs as well as merge entire files together.
  21. """
  22. import PyPDF2
  23. import os
  24. import random
  25. import logging
  26. import argparse
  27.  
  28. logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
  29. logging.disable(logging.CRITICAL)
  30.  
  31. def set_password(input_file, owner_pass):
  32.     """
  33.    Function creates new temporary pdf file with same content,
  34.    assigns given password to pdf and rename it with original file.
  35.    temporary output file with name same as input file but prepended
  36.     by "encrypted_", inside same direcory as input file.
  37.    """
  38.     path, filename = os.path.split(input_file)
  39.     output_file = os.path.join(path, "encrypted_" + filename)
  40.  
  41.     output = PyPDF2.PdfFileWriter()
  42.  
  43.     input_stream = PyPDF2.PdfFileReader(open(input_file, "rb"))
  44.  
  45.     for i in range(0, input_stream.getNumPages()):
  46.         output.addPage(input_stream.getPage(i))
  47.  
  48.     #try:
  49.     #    outputStream = open(output_file, "wb")
  50.     #except PermissionError:
  51.     #    raise Exception("[Errno 13] Permission denied: '%s'" % (output_file))
  52.     outputStream = open(output_file, "wb")
  53.  
  54.     """/
  55.    encrypt(user_pwd, owner_pwd=None, use_128bit=True)
  56.    Encrypt this PDF file with the PDF Standard encryption handler.
  57.     Parameters:
  58.        user_pwd (str) – The “user password”, which allows for opening and reading the PDF file with the restrictions provided.
  59.        owner_pwd (str) – The “owner password”, which allows for opening the PDF files without any restrictions. By default, the owner password is the same as the user password.
  60.        use_128bit (bool) – flag as to whether to use 128bit encryption. When false, 40bit encryption will be used. By default, this flag is on.
  61.    """
  62.     # Set owner password to pdf file
  63.     output.encrypt('', owner_pass, use_128bit=True)
  64.    
  65.     output.write(outputStream)
  66.     outputStream.close()
  67.  
  68. def get_password():
  69.     text_string = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()'
  70.     password = ''.join(random.sample(text_string, 32))
  71.     logging.info("Password = '%s'" % password)
  72.     return password
  73.  
  74. def main():
  75.     parser = argparse.ArgumentParser()
  76.     parser.add_argument('-i', '--input_pdf', required=True, help='Input PDF file')
  77.     args = parser.parse_args()
  78.     set_password(args.input_pdf, get_password())
  79.  
  80. if __name__ == "__main__":
  81.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement