def test_block_encryption_and_normalize(trivial, outpdf): with pytest.raises(ValueError, match=r'encryption and normalize_content'): trivial.save( outpdf, encryption=pikepdf.Encryption(owner='foo', user='******'), normalize_content=True, )
def encrypt_decrypt(): #The function to encrypt or decrypt the PDF. print(Style.BRIGHT + Fore.CYAN + '\nEnter Your Option:\n') print(Style.BRIGHT + Fore.YELLOW + '1 - Encrypt') print(Style.BRIGHT + Fore.YELLOW + '2 - Decrypt') print(Style.BRIGHT + Fore.RED + '\nYour Option >>>', end=' ') n = int(input()) if (n != 1 and n != 2): raise ValueError('Please enter only the above given Numerical Values') print(Style.BRIGHT + Fore.BLUE + '\nEnter the Password for the PDF File:', end=" ") password = input() if (n == 1): input_path, filename = get_path() out_path = os.path.join(os.getcwd(), 'encrypted_' + filename) pdf = pikepdf.Pdf.open(os.path.join(input_path, filename)) pdf.save(out_path, encryption=pikepdf.Encryption(owner=password, user=password, R=4)) # you can change the R from 4 to 6 for 256 aes encryption pdf.close() print(Style.BRIGHT + Fore.RED + '\n----------FINISHED------------') if (n == 2): input_path, filename = get_path() out_path = os.path.join(os.getcwd(), 'decrypted_' + filename) pdf = pikepdf.open(os.path.join(input_path, filename), password=password) pdf.save(out_path) pdf.close() print(Style.BRIGHT + Fore.RED + '\n----------FINISHED------------')
def encrypt(self, own_passwd, usr_passwd): file_path=os.path.join(self.project_path, self.pdf_name) if not os.path.exists(file_path): print("Pdf for encryption does not exist.") try: import pikepdf except: print("For encryption must be enabled import of pikepdf packge.") print("Exitting encrypt.") return permiss=pikepdf.Permissions(accessibility=True, extract=True, modify_annotation=True, modify_assembly=False, modify_form=False, modify_other=False, print_highres=True, print_lowres=True) encrypt=pikepdf.Encryption(user=usr_passwd, owner=own_passwd, allow=permiss) pdf=pikepdf.Pdf.open(file_path,allow_overwriting_input=True) pdf.save(file_path, encryption=encrypt) pdf.close() del pikepdf
def test_bad_settings(trivial, outpdf, R, owner, user, aes, metadata, err): with pytest.raises(Exception, match=err): trivial.save( outpdf, encryption=pikepdf.Encryption( R=R, owner=owner, user=user, aes=aes, metadata=metadata ), )
def test_encrypt_permissions_deny(trivial, outpdf): perms = pikepdf.models.Permissions(extract=False) trivial.save( outpdf, encryption=pikepdf.Encryption(owner='sun', user='******', allow=perms) ) with pikepdf.open(outpdf, password='******') as pdf: assert not pdf.allow.extract assert pdf.allow.modify_form
def password_protect_files(self, password): for file_name in self.model.get_files_for_processing(): pdf = Pdf.open(file_name) pdf.save(os.path.splitext(file_name)[0] + '_pw.pdf', encryption=pikepdf.Encryption(owner=password, user=password, R=4)) pdf.close() self.model.remove_all_files()
def protect(file, password=password): ''' This function takes a file as an input and creates another file in the same destination This file is encrypted with the password defined earlier ''' pdf = Pdf.open(file) pdf.save(os.path.splitext(file)[0] + '_encrypted.pdf', encryption=pikepdf.Encryption(owner=password, user=password, R=4)) # you can change the 4 to 6 for 256 aes encryption but that file won't open on Acrobat versions lower than 10.0 pdf.close() return
def encrypt(filename, destination, password): if not isDirValid(destination): raise Exception( "The file directory may be removed or renamed.\nPlease try again") if not isFileValid(filename): raise Exception( "The file may be deleted or renamed.\nPlease try again") pdf = Pdf.open(filename) newName = filename.split("/")[-1].split(".")[0] + '_encrypted.pdf' pdf.save(destination + "/" + newName, encryption=pikepdf.Encryption(owner=password, user=password, R=4))
def encrypt_pdf(file, password): """ This function encrypts the PDF `file` using the provided password. Parameters ---------- file : string The file to be encrypted using AES 256. password : string The owner password for the encryption (per PyMuPDF settings) Returns ------- None. """ # Set the appropriate permissions permissions = pikepdf.Permissions( accessibility=True, extract=False, modify_annotation=False, modify_assembly=False, modify_form=False, modify_other=False, print_lowres=True, print_highres=True, ) # Get a temporary filename tmpfile = next(tempfile._get_candidate_names()) tmpfile += ".pdf" # make a copy of the PDF shutil.copyfile(file, tmpfile) # Remove the original file os.remove(file) # Open the tempfile and save as the encrypted file pdf = pikepdf.Pdf.open(tmpfile) pdf.save( file, encryption=pikepdf.Encryption(owner=password, user="", R=6, allow=permissions), ) # Now close and delete the tempfile pdf.close() os.remove(tmpfile)
def encrypt_PDF(sourceFileName=''): p = Path(__file__).with_name(sourceFileName) pdf = pikepdf.Pdf.open(p, allow_overwriting_input=True) pdfRestrictions = pikepdf.Permissions(accessibility=False, extract=False, print_lowres=False, print_highres=False, modify_annotation=False, modify_assembly=False, modify_form=False, modify_other=False) pdf.save(sourceFileName, encryption=pikepdf.Encryption(user="", owner=pdfPassword, allow=pdfRestrictions))
def lock_PDf(source_folder, destination_folder, password): count = 0 for item in os.scandir(source_folder): if ".pdf" in item.name: file_name = item.name mypdf = pikepdf.open( source_folder + "/" + file_name) # open the unlocked pdf in source folder mypdf.save(destination_folder + "/" + file_name, encryption=pikepdf.Encryption(owner=password, user=password) ) # save the locked pdf in destination folder print("\t\"" + file_name + "\"" + " locked") count = count + 1 return count
def _protect(): #Selects, opens, then encrypts and saves a copy of the PDF new_save_location = os.path.join(output, os.path.split(original_path)[1]) if batch_protect == False: try: original_file = Pdf.open(original_path, password="") except FileNotFoundError: return else: original_file.save(os.path.splitext(new_save_location)[0] + "_encrypted.pdf", encryption=pikepdf.Encryption(owner=password, user=password, R=6)) original_file.close() return msg.showinfo( "Complete", f"You have successfully encrypted {os.path.splitext(new_save_location)[0] + '_encrypted.pdf'}\nWith the password: {password}" ) else: for folder, subfolders, files in os.walk(batch_input): for file in files: if file.endswith((".pdf", ".PDF")): pass
# todo 使用Python的pikepdf模块,即可对文件进行加密,写一个循环就能进行批量加密文档。 # todo 如果你有100个或更多的PDF文件需要加密,手动进行加密肯定是不可行的,极其浪费时间。 # PDF加密 import pikepdf pdf = pikepdf.open("test.pdf") pdf.save('encrypt.pdf', encryption=pikepdf.Encryption(owner="your_password", user="******", R=4)) pdf.close() # PDF解密 import pikepdf pdf = pikepdf.open("encrypt.pdf", password='******') pdf.save("decrypt.pdf") pdf.close()
def encrypt_and_add_metadata(input_pdf, output_folder, usr_pass, owner_pass, remove_original=False): """Encrypts PDF, changes permissions and adds metadata to PDF. Default permissions let the user to print PDF but all other operations are restricted. In case you do not want to allow reading without a password, specify `usr_pass`. If you want to remove the original PDF after encryption set the `remove_original` parameter to `True` Args: input_pdf (str): path to input PDF output_folder (str): path to output folder usr_pass (str): user password to open PDF, if "", no pass required. owner_pass (str): owner password to edit PDF remove_original (bool, optional): Whether remove prior processed file(s) or not. Defaults to False. """ # Extract file_name from the path file_name = input_pdf.split(os.sep)[-1].split('.')[0] # Set output path of PDF output_pdf = os.path.join(output_folder, file_name + '_final' + '.pdf') # Metadata sections of PDF. For more information visit the link below. # https://www.adobe.io/open/standards/xmp.html#!adobe/xmp-docs/master/Namespaces.md # Dublin Core namespace: dc:title, dc:creator, dc:description, dc:subject, dc:format, dc:rights # XMP basic namespace: xmp:CreateDate, xmp:CreatorTool, xmp:ModifyDate, xmp:MetadataDate # XMP rights management namespace: xmpRights:WebStatement, xmpRights:Marked # XMP media management namespace: xmpMM:DocumentID pdf = pikepdf.Pdf.open(input_pdf) # Read PDF with pdf.open_metadata() as meta: # Add Metadata meta['dc:title'] = 'Lecture Notes' meta['dc:creator'] = 'Serhan Yarkan, Tapir Lab.' # Author meta['dc:description'] = 'Tapir Lab. Fall-2020 Lecture Notes' meta['dc:subject'] = 'Probability, statistics, communications...\n\ ALL HAIL TAPIR!\n\ tapirlab.com' # Keywords meta['dc:rights'] = 'Tapir Lab. License' meta['xmp:CreateDate'] = datetime.today().isoformat() meta['xmp:ModifyDate'] = datetime.today().isoformat() meta['xmp:CreatorTool'] = "Tapir Lab.'s Automatic Watermarking Script" meta['xmpRights:WebStatement'] = "http://www.tapirlab.com" # Set permissions of user permissions = pikepdf.Permissions( accessibility=False, extract=False, modify_annotation=False, modify_assembly=False, modify_form=False, modify_other=False, print_lowres=True, print_highres=True, ) # Save PDF with added metadata and restricted permissions. pdf.save(output_pdf, encryption=pikepdf.Encryption( user=usr_pass, owner=owner_pass, allow=permissions, )) # Close PDF object pdf.close() if remove_original: # Remove original file if True os.remove(input_pdf)
import pikepdf import os file_name = os.listdir() print(file_name) old_password = "******" new_password = "******" for file in file_name: pdf = pikepdf.open(file, password=old_password) pdf.save("NEW" + file, encryption=pikepdf.Encryption(owner=new_password, user=new_password, R=6)) pdf.close