DEV Community

loading...
Cover image for Python Scripts- AES Encryption in Python

Python Scripts- AES Encryption in Python

envoy_ profile image Envoy-VC Updated on ・1 min read

For this tutorial we will need the following Python library:

cryptography



If you don’t have it installed, please open “PowerShell” or "Terminal" (on Windows) and install it using the following code:

pip install cryptography
Enter fullscreen mode Exit fullscreen mode

Working

The cryptography is a special AES encryption module. It means that you have to generate a special token to encrypt a file and to decrypt that same file you need to have that same key/token which was used to encrypt the file. This is more secure than other encryptions because no other person has access to the token

Importing Modules

from cryptography.fernet import Fernet
Enter fullscreen mode Exit fullscreen mode

Generating and storing the unique Key

def write_key():
    key = Fernet.generate_key()
    with open("key.key", "wb") as key_file:
        key_file.write(key)
Enter fullscreen mode Exit fullscreen mode

Loading the Key

def load_key():
    return open("key.key", "rb").read()
Enter fullscreen mode Exit fullscreen mode

Encrypt Function

def encrypt(filename, key):
    f = Fernet(key)
    with open(filename, "rb") as file:
        file_data = file.read()
    encrypted_data = f.encrypt(file_data)
    with open(f'{filename}.enc', "wb") as file:
        file.write(encrypted_data)
Enter fullscreen mode Exit fullscreen mode

Decrypt Function

def decrypt(filename, key):
    f = Fernet(key)
    with open(f'{filename}.enc', "rb") as file:
        # read the encrypted data
        encrypted_data = file.read()
    # decrypt data
    decrypted_data = f.decrypt(encrypted_data)
    with open(f'{filename}.dec', "wb") as file:
        file.write(decrypted_data)
Enter fullscreen mode Exit fullscreen mode

Actual Working

write_key()

# AFTER RUNNING THE FILE FOR THE FIRST TIME COMMENT 
# OUT THE ABOVE LINE TO PREVENT OVERWRITING OF TKE 'KEY.KEY'
# FILE 

#LOADING THE KEY
key = load_key()

file = 'YOUR FILENAME HERE'

#THIS FUNCTION FOR ENCRYPTION  
encrypt(file,key)

#THIS FUNCTION FOR DECRYPTION
decrypt(file,key)
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide