Decrypt encrypted files using Python

Learn Python @

Introduction to File Decryption with Python

Decrypting files is a common task in cybersecurity and data security. In this article, we’ll explore how to decrypt encrypted files using Python. We’ll discuss the concepts involved, walk through the decryption process step-by-step, and provide a script example for practical implementation.

Understanding Encryption and Decryption

Encryption is the process of converting plaintext data into ciphertext using an encryption algorithm and a secret key. Decryption, on the other hand, is the reverse process of converting ciphertext back into plaintext using the same algorithm and key.

Decryption Process Overview

To decrypt an encrypted file, we need the encrypted file itself and the secret key used for encryption. The decryption process involves reading the encrypted file, applying the decryption algorithm with the secret key, and writing the decrypted data to a new file.

Writing the Decryption Script in Python

Let’s create a Python script that takes an encrypted file as an argument and decrypts it using the PyCryptodome library, a popular cryptography library in Python.

from Crypto.Cipher import AES

def decrypt_file(encrypted_file, key):
    cipher =, AES.MODE_ECB)
    with open(encrypted_file, 'rb') as f:
        encrypted_data =
    decrypted_data = cipher.decrypt(encrypted_data)
    with open('decrypted_file.txt', 'wb') as f:
if __name__ == '__main__':
    import sys
    if len(sys.argv) < 3:
        print("Usage: python <encrypted_file> <key> : Learning @ ")
    encrypted_file = sys.argv[1]
    key = sys.argv[2]
    decrypt_file(encrypted_file, key)
  • We import the AES module from the Crypto.Cipher package to use the AES encryption algorithm.
  • The decrypt_file function takes the path to the encrypted file and the decryption key as arguments.
  • Inside the function, we create an AES cipher object using the provided key and the ECB mode.
  • We read the contents of the encrypted file, decrypt the data using the cipher object, and write the decrypted data to a new file named “decrypted_file.txt”.

Example Usage and Output

Let’s assume we have an encrypted file named “encrypted_data.txt” and a key “mysecretkey”.

$ python encrypted_data.txt mysecretkey

After running the script, a new file named “decrypted_file.txt” will be created with the decrypted contents of the encrypted file.

Author: user