DEV Community

Free Python Code
Free Python Code

Posted on

Encrypt And Decrypt files in Python

Hi 🙂🖐

Welcome in a new post, Today i will show you how to Encrypt And Decrypt files in Python and module called cryptography.

step 1

install cryptography

pip install cryptography

step 2

Generate key to use it in encrypt and decrypt process

from cryptography.fernet import Fernet
from os import remove


# #generate the key 
# key = Fernet.generate_key()
# print(key)
Enter fullscreen mode Exit fullscreen mode

Encyrept file

f = Fernet(key)

def encrypt(fname):
   with open(fname, 'rb') as f1:
        with open(fname + '.enc', 'wb') as f2:
            f2.write(f.encrypt(f1.read()))

    remove(fname)
Enter fullscreen mode Exit fullscreen mode

Decrypt file

def decrypt(fname):
    with open(fname, 'rb') as f1:
        with open(fname.replace('.enc', ''), 'wb') as f2:
            f2.write(f.decrypt(f1.read()))

    remove(fname)
Enter fullscreen mode Exit fullscreen mode

Now we're done 🤗

Don't forget to like and follow 🙂

Support me on PayPal 🤗
https://www.paypal.com/paypalme/amr396

Top comments (0)