File Locker CLI

import argparse

import getpass

import os

from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

from cryptography.hazmat.backends import default_backend

from cryptography.hazmat.primitives import hashes

from cryptography.fernet import Fernet

import base64


def derive_key(password: str, salt: bytes) -> bytes:

    kdf = PBKDF2HMAC(

        algorithm=hashes.SHA256(),

        length=32,

        salt=salt,

        iterations=390000,

        backend=default_backend()

    )

    return base64.urlsafe_b64encode(kdf.derive(password.encode()))


def encrypt_file(filepath, password):

    with open(filepath, 'rb') as file:

        data = file.read()


    salt = os.urandom(16)

    key = derive_key(password, salt)

    fernet = Fernet(key)

    encrypted_data = fernet.encrypt(data)


    with open(filepath + ".locked", 'wb') as file:

        file.write(salt + encrypted_data)


    os.remove(filepath)

    print(f"🔒 File encrypted as {filepath}.locked")


def decrypt_file(filepath, password):

    with open(filepath, 'rb') as file:

        content = file.read()


    salt = content[:16]

    encrypted_data = content[16:]

    key = derive_key(password, salt)

    fernet = Fernet(key)


    try:

        decrypted_data = fernet.decrypt(encrypted_data)

    except Exception:

        print("❌ Wrong password or corrupted file.")

        return


    original_path = filepath.replace(".locked", "")

    with open(original_path, 'wb') as file:

        file.write(decrypted_data)


    os.remove(filepath)

    print(f"🔓 File decrypted as {original_path}")


def main():

    parser = argparse.ArgumentParser(description="🔐 File Locker CLI")

    parser.add_argument("action", choices=["lock", "unlock"], help="Lock or unlock the file")

    parser.add_argument("filepath", help="Path to the file")


    args = parser.parse_args()

    password = getpass.getpass("Enter password: ")


    if args.action == "lock":

        encrypt_file(args.filepath, password)

    elif args.action == "unlock":

        decrypt_file(args.filepath, password)


if __name__ == "__main__":

    main()


No comments: