假设我们有一个名为input.pdf的文件,我们将创建一个新的加密文件output.pdf,并设置密码为mysecretpassword。 importPyPDF2defencrypt_pdf(input_file,output_file,password):# 打开原始PDF文件withopen(input_file,'rb')asfile:reader=PyPDF2.PdfReader(file)writer=PyPDF2.PdfWriter()# 将所有页面添加到写入器...
pdf_writer.addPage(pdf_reader.getPage(page)) pdf_writer.encrypt(password) # 写入密码并输出到目的路径 with open(rosterNow, 'wb') as out: pdf_writer.write(out) print("文件:%s---已完成加密,密码为:%s"%(rosterLast,password)) # 函数入口 if __name__ == '__main__': print("---开始...
It is a completely readable file. To encrypt it, all we need to do is call the function we just wrote: # uncomment this if it's the first time you run the code, to generate the key# write_key()# load the keykey=load_key()# file namefile="data.csv"# encrypt itencrypt(file,ke...
algorithm.block_size) with open(output_file_path, "wb") as decrypted_file: decrypted_file.write(unpadded_data) # 示例使用 encrypt_file("original.txt", "encrypted.bin", key) decrypt_file("encrypted.bin", "decrypted.txt", key) 6.2.2 使用GPG进行文件加密 GnuPG(Gnu Privacy Guard)是一种流...
importPyPDF2defencrypt_pdf(input_pdf, output_pdf, password):#打开PDF文件with open(input_pdf,'rb') as file:#创建PDF写入对象pdf_writer =PyPDF2.PdfWriter()#创建PDF阅读器对象pdf_reader =PyPDF2.PdfReader(file)#遍历每一页并添加到写入对象中forpage_numinrange(len(pdf_reader.pages)): ...
) encrypted_data = cipher_suite.encrypt(data) with open(file_path + '.encrypted', 'wb') as file: file.write(encrypted_data) # 加密前的明文文件路径 file_path = 'path/to/your/file.txt' # 密码,可以是任意字符串,但必须保密 password = b'your_password' encrypt_file(file_path, password)...
- 加密文件内容:使用私钥对文件内容进行加密。这可以通过调用`rsa.encrypt()`函数来实现,其中`file_content`是要加密的文件内容,`public_key`是公钥对象。 - 解密文件内容:使用公钥对文件内容进行解密。这可以通过调用`rsa.decrypt()`函数来实现,其中`encrypted_content`是加密后的文件内容,`private_key`是私钥对象...
import os import hashlib def encrypt_directory(directory, password): for root, dirs, files in os.walk(directory): for file in files: path = os.path.join(root, file) with open(path, 'rb') as f: data = f.read() key = hashlib.sha256(password.encode()).hexdigest() encrypted_data ...
writer.encrypt(password) # 将加密后的 PDF 写入新的文件 with open(output_pdf_path, 'wb') as output_file: writer.write(output_file) print(f"PDF 文件已加密并保存为 {output_pdf_path}") 3、运行脚本: 在命令行中运行脚本: python set_pdf_password.py ...
(public_key_file,"rb")askey_file:public_key=rsa.PublicKey.load_pkcs1(key_file.read())# 加密文件内容encrypted_content=rsa.encrypt(file_content,public_key)# 将加密后的内容写入文件withopen(file_path,"wb")asfile:file.write(encrypted_content)defdecrypt_file(file_path,private_key_file,password)...