【问题标题】:PDF file encryption and decryption in python with fernet key使用fernet密钥在python中对PDF文件进行加密和解密
【发布时间】:2022-12-30 10:36:43
【问题描述】:

我正在尝试加密 pdf 文件,然后尝试解密以使用 fernet 密钥获取其数据。 我能够成功加密它但是在解密它时,我得到的是二进制流而不是实际数据,请帮忙。 (假设所有需要的模块都被导入并且 pdf 作为数据作为嗨,你好吗在 2 行中)加密:

def encrypt_file(file_path,file_name):
    try:
        fernet=Fernet(fernet_key)
        print("Created fernet object")
        file=os.path.join(file_path,file_name)
        with open(file,'rb') as f:
            data=f.read()
        try:
            data_enc=fernet.encrypt(data)
        except Exception as e:
            e_msg="".join(traceback.format_exception(*sys.exc_info()))
            print("An occured during data encryption, reason: "+str(e)+"Error: "+e_msg)
            return False
        with open(file,'wb') as f:
            f.write(data_enc)
        print("Encryption Successful")
    except Exception as e:
        print("An occured while encrypting the file, reason: "+str(e)+"Error: "+e_msg)
        return False
    return True

解密:

def decrypt_data(file_path,file_name):
    try:
        data=''
        fernet=Fernet(fernet_key)
        file=os.path.join(file_path,file_name)
        with open(file,'rb') as f:
            data_enc=f.read()
        try:
            data=fernet.decrypt(data_enc)
            data=data.decode()
        except Exception as e:
            e_msg="".join(traceback.format_exception(*sys.exc_info()))
            print("An occured during data decryption, reason: "+str(e)+"Error: "+e_msg)
    except Exception as e:
        e_msg="".join(traceback.format_exception(*sys.exc_info()))
        print("An occured while decrypting the file, reason: "+str(e)+"Error: "+e_msg)
        return False

    return data

输出(修整)ZxM6cMB3Ou8xWZQ4FpZVUKelqo11TcJr_Js7LFo-0XpU05hsIX0pz88lqEfLmY_TSZQWHuYb1yulBT3FYBTd-QU0RqPlPsCSkH3z_LIHyIie5RO7Rztgxs2Y2zyAzkoNQ9M52hhqNgybTE8K_OzQGb9clOTKdkidCW4VTH77HGbSP1EK-x3lTTmVVf0m-

【问题讨论】:

  • 你能加密和解密一个简单的文本文件吗?试试看,看看它是否有效。如果没有,那么您的加密或解密都有问题。如果是,那么您的 PDF 文件有问题。或许您需要仔细检查您是否在整个过程的所有阶段都期待一个二进制文件,而不是其他格式。

标签: python pdf encryption cryptography fernet


【解决方案1】:

如果你只是想加密和解密一个pdf文件,你不需要data=data.decode()。相反,您可以通过将以下代码附加到您的 decrypt_data 函数来写入输出 pdf。

f=open(os.path.join(file_path, "output.pdf"), "wb")
f.write(data)

现在如果你打开output.pdf,它将是解密后的pdf。

如果您只想要一个带有 pdf 中可读文本的字符串,那么查看 pdf 阅读库(例如 PyPDF2)可能会有所帮助。

【讨论】:

    猜你喜欢
    • 2021-02-15
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    相关资源
    最近更新 更多