0

I'm trying to encrypt the pdf file and then trying to decrypt to get its data with fernet key. i'm able to encrypt it successfully but while decrypting it, i'm getting a binary stream not the actual data, please help. (assume all the needed modules are imported and pdf as data as Hi, how are you in 2 lines) Encryption:

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

Decryption:

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

OUTPUT (trimmed) ZxM6cMB3Ou8xWZQ4FpZVUKelqo11TcJr_Js7LFo-0XpU05hsIX0pz88lqEfLmY_TSZQWHuYb1yulBT3FYBTd-QU0RqPlPsCSkH3z_LIHyIie5RO7Rztgxs2Y2zyAzkoNQ9M52hhqNgybTE8K_OzQGb9clOTKdkidCW4VTH77HGbSP1EK-x3lTTmVVf0m-

Abhishek K M
  • 43
  • 1
  • 5
  • 1
    Can you encrypt and decrypt a simple text file? Try that, and see if it works. If it doesn't then you have a problem with either encryption of decryption. If it does, then you have a problem with the PDF file. Perhaps you need to check carefully that you are expecting, essentially, a binary file, not some other format, at all stages of the process. – rossum Aug 22 '22 at 15:12

1 Answers1

0

If you just want to encrypt and decrypt a pdf file, you don't need the data=data.decode(). Instead, you can write to an output pdf by appending the code below to your decrypt_data function.

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

Now if you open output.pdf, it will be the decrypted pdf.

If you only want a string with the readable text in the pdf, then it may help to look into pdf reading libraries such as PyPDF2.