How to encrypt files and Directories in Python

0

In this python project, you will see how we can encrypt files and directories in python. we have started a series of python projects and this is a part of that 100+ python project series. You will learn how you can do encryption.

Also Check: Python Libraries for Cryptography

Encrypt Files and Directories in Python

We have used different python packages to do file encryption in python. Check the following code along with requirements and run it in your Python IDE and you will see how you can encrypt files and directories.

encrypt files in python

Requirements:

You need to have python installed

You need to have pip installed

You need to have install pycryptodome

pip install pycryptodome

Python code to Encrypt Files and Directories


import sys
import os
from Cryptodome.Cipher import AES
from Cryptodome import Random
from binascii import b2a_hex


def encrypt_dir(path):
    for root, _, files in os.walk("."):
        for file in files:
            file_path = os.path.join(root, file)
            print(file_path + " is encrypting.")
            encrypt_file(file_path)


def encrypt_file(path):
    # get the plaintext
    with open(path) as f:
        plain_text = f.read()

    # The key length must be 16 (AES-128), 24 (AES-192), or 32 (AES-256) Bytes.
    key = b'this is a 16 key'

    iv = Random.new().read(AES.block_size)
    mycipher = AES.new(key, AES.MODE_CFB, iv)
    ciphertext = iv + mycipher.encrypt(plain_text.encode())

    # output
    with open(path + ".bin", "wb") as file_out:
        file_out.write(ciphertext[16:])


path = sys.argv[1]
if os.path.isdir(path) and os.path.exists(path):
    encrypt_dir(path)
elif os.path.isfile(path) and os.path.exists(path):
    encrypt_file(path)
else:
    print("it's a special file(socket,FIFO,device file)")

Related Python Projects

Summary and Conclusion

You have seen how you can do encryption in python. You will see more python projects so make sure you bookmark my site and let me know if you have any questions.

Post a Comment

0Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !