Advertisement
DrAungWinHtut

aes_no_salt.py

Dec 1st, 2023
967
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.11 KB | None | 0 0
  1. import os
  2. from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
  3. from cryptography.hazmat.backends import default_backend
  4. from hashlib import sha256
  5.  
  6. # Function to generate a key from the password
  7. def generate_key(password: str) -> bytes:
  8.     return sha256(password.encode()).digest()
  9.  
  10. # Function to encrypt a file
  11. def encrypt_file(file_path: str, key: bytes):
  12.     iv = os.urandom(16)  # Generate a random IV
  13.     cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
  14.     encryptor = cipher.encryptor()
  15.  
  16.     with open(file_path, 'rb') as file:
  17.         original = file.read()
  18.  
  19.     encrypted = encryptor.update(original) + encryptor.finalize()
  20.  
  21.     with open(file_path, 'wb') as encrypted_file:
  22.         encrypted_file.write(iv + encrypted)  # Prepend the IV for decryption
  23.  
  24. # Function to decrypt a file
  25. def decrypt_file(file_path: str, key: bytes):
  26.     with open(file_path, 'rb') as file:
  27.         iv = file.read(16)  # Read the IV from the file
  28.         encrypted = file.read()
  29.  
  30.     cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
  31.     decryptor = cipher.decryptor()
  32.     decrypted = decryptor.update(encrypted) + decryptor.finalize()
  33.  
  34.     with open(file_path, 'wb') as decrypted_file:
  35.         decrypted_file.write(decrypted)
  36.  
  37. # Function to process all files in a directory
  38. def process_files(folder_path: str, password: str, mode: str):
  39.     key = generate_key(password)
  40.  
  41.     for filename in os.listdir(folder_path):
  42.         file_path = os.path.join(folder_path, filename)
  43.         if os.path.isfile(file_path):
  44.             if mode == 'encrypt':
  45.                 encrypt_file(file_path, key)
  46.                 print(f"Encrypted {filename}")
  47.             elif mode == 'decrypt':
  48.                 decrypt_file(file_path, key)
  49.                 print(f"Decrypted {filename}")
  50.  
  51. # Main function
  52. def main():
  53.     folder_path = input("Enter the folder path: ")
  54.     password = input("Enter password: ")
  55.     mode = input("Enter mode (encrypt/decrypt): ").lower()
  56.     process_files(folder_path, password, mode)
  57.  
  58. if __name__ == "__main__":
  59.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement