Skip to content

Advanced Encryption Tool Β #6

@poorni286

Description

@poorni286

Here's a complete explanation of the AES-256 Encryption Tool for your CodTech Internship Task-4, along with the Python code broken down step by step.


βœ… Project Title: Advanced Encryption Tool using AES-256


πŸ”’ What is AES-256?

AES (Advanced Encryption Standard) is a symmetric encryption algorithm used worldwide for secure data encryption.

256-bit key: Makes it very strong and resistant to brute-force attacks.

CBC Mode (Cipher Block Chaining): Encrypts data block by block with an Initialization Vector (IV) for randomness.


🎯 Project Objective

Create a Python-based tool to:

  1. Encrypt and decrypt files using AES-256.

  2. Have a simple GUI (Graphical User Interface) using tkinter.


πŸ“¦ Libraries Used

Library Purpose

cryptography AES encryption and key derivation
tkinter To build a simple GUI
os, base64 File handling and random byte generation


πŸ”§ How It Works (Concept)

πŸ” Encryption:

  1. Get file data and password from user.

  2. Generate a random salt and IV.

  3. Derive a 256-bit encryption key from password using PBKDF2.

  4. Encrypt file data using AES-256 in CBC mode.

  5. Save the encrypted file with .enc extension.

πŸ”“ Decryption:

  1. Read encrypted file, extract salt, IV, and encrypted content.

  2. Re-derive the key from password and salt.

  3. Decrypt content using AES-256.

  4. Save the decrypted file.


🧠 Complete Code with Comments

import os
import base64
import tkinter as tk
from tkinter import filedialog, messagebox
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

Constants

KEY_SIZE = 32 # 256 bits
IV_SIZE = 16 # 128-bit IV
SALT_SIZE = 16 # Salt for key derivation
backend = default_backend()

πŸ”‘ Derive a secure AES key from password

def derive_key(password: str, salt: bytes) -> bytes:
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=KEY_SIZE,
salt=salt,
iterations=100000,
backend=backend
)
return kdf.derive(password.encode())

πŸ” Encrypt the file

def encrypt_file(file_path, password):
with open(file_path, 'rb') as f:
data = f.read()

salt = os.urandom(SALT_SIZE)         # Random salt
iv = os.urandom(IV_SIZE)             # Random IV
key = derive_key(password, salt)     # Generate AES key

cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
encryptor = cipher.encryptor()

# PKCS#7 Padding
padding_len = 16 - len(data) % 16
data += bytes([padding_len]) * padding_len

ct = encryptor.update(data) + encryptor.finalize()

encrypted_data = salt + iv + ct
enc_file = file_path + '.enc'

with open(enc_file, 'wb') as f:
    f.write(encrypted_data)

return enc_file

πŸ”“ Decrypt the file

def decrypt_file(file_path, password):
with open(file_path, 'rb') as f:
encrypted_data = f.read()

salt = encrypted_data[:SALT_SIZE]
iv = encrypted_data[SALT_SIZE:SALT_SIZE + IV_SIZE]
ct = encrypted_data[SALT_SIZE + IV_SIZE:]

key = derive_key(password, salt)

cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
decryptor = cipher.decryptor()

data = decryptor.update(ct) + decryptor.finalize()

# Remove padding
padding_len = data[-1]
data = data[:-padding_len]

dec_file = file_path.replace('.enc', '') + '_decrypted'
with open(dec_file, 'wb') as f:
    f.write(data)

return dec_file

πŸ“ File selector

def select_file():
path = filedialog.askopenfilename()
entry_file.delete(0, tk.END)
entry_file.insert(0, path)

πŸ”˜ GUI Action - Encrypt

def encrypt_action():
path = entry_file.get()
pwd = entry_pass.get()
if not path or not pwd:
messagebox.showwarning("Missing Info", "Please select a file and enter a password.")
return
try:
out_file = encrypt_file(path, pwd)
messagebox.showinfo("Success", f"File encrypted:\n{out_file}")
except Exception as e:
messagebox.showerror("Error", str(e))

πŸ”˜ GUI Action - Decrypt

def decrypt_action():
path = entry_file.get()
pwd = entry_pass.get()
if not path or not pwd:
messagebox.showwarning("Missing Info", "Please select a file and enter a password.")
return
try:
out_file = decrypt_file(path, pwd)
messagebox.showinfo("Success", f"File decrypted:\n{out_file}")
except Exception as e:
messagebox.showerror("Error", str(e))

πŸ–₯️ GUI Interface

app = tk.Tk()
app.title("AES-256 Encryption Tool")

tk.Label(app, text="File Path:").pack()
entry_file = tk.Entry(app, width=50)
entry_file.pack()
tk.Button(app, text="Browse", command=select_file).pack()

tk.Label(app, text="Password:").pack()
entry_pass = tk.Entry(app, show='*', width=50)
entry_pass.pack()

tk.Button(app, text="Encrypt", command=encrypt_action, bg="green", fg="white").pack(pady=5)
tk.Button(app, text="Decrypt", command=decrypt_action, bg="blue", fg="white").pack(pady=5)

app.mainloop()


πŸ§ͺ Example

  1. Run the script β†’ GUI appears.

  2. Browse and select a file.

  3. Enter a password β†’ Click Encrypt β†’ Saves .enc file.

  4. Use same password to decrypt β†’ Gets back original data.


πŸ“„ Output

Encrypted file: example.txt.enc

Decrypted file: example.txt_decrypted


πŸ“‹ Deliverables (as per internship task)

βœ… Python script
βœ… Uses AES-256
βœ… Encrypts & decrypts files
βœ… User-friendly interface (GUI)
βœ… Strong password-based security


πŸ“¦ Optional Add-ons

Let me know if you'd like help with:

πŸ”§ Creating a standalone .exe (using PyInstaller)

🌐 Web interface (using Flask)

πŸ”’ File type filters or logs

Would you like a report (PDF/Docx) format for submission too?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions