Advertisement
xGHOSTSECx

In The Year 2048...

Dec 24th, 2023
1,218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.38 KB | None | 0 0
  1. import os
  2. import zipfile
  3. from cryptography.hazmat.primitives import serialization, hashes
  4. from cryptography.hazmat.primitives.asymmetric import rsa, padding
  5. from cryptography.fernet import Fernet
  6. import hashlib
  7.  
  8. # Generate or load RSA keys
  9. def generate_rsa_keypair(key_size=4096):
  10.     private_key = rsa.generate_private_key(
  11.         public_exponent=65537,
  12.         key_size=key_size
  13.     )
  14.     return private_key, private_key.public_key()
  15.  
  16. def save_rsa_key(key, filename, passphrase=None):
  17.     with open(filename, "wb") as key_file:
  18.         if passphrase:
  19.             key_pem = key.private_bytes(
  20.                 encoding=serialization.Encoding.PEM,
  21.                 format=serialization.PrivateFormat.PKCS8,
  22.                 encryption_algorithm=serialization.BestAvailableEncryption(passphrase),
  23.             )
  24.         else:
  25.             key_pem = key.private_bytes(
  26.                 encoding=serialization.Encoding.PEM,
  27.                 format=serialization.PrivateFormat.PKCS8,
  28.                 encryption_algorithm=serialization.NoEncryption()
  29.             )
  30.         key_file.write(key_pem)
  31.  
  32. def load_rsa_key(filename, passphrase=None):
  33.     with open(filename, "rb") as key_file:
  34.         key_pem = key_file.read()
  35.         if passphrase:
  36.             return serialization.load_pem_private_key(key_pem, passphrase)
  37.         else:
  38.             return serialization.load_pem_private_key(key_pem, None)
  39.  
  40. # Encrypt a file using Fernet symmetric encryption
  41. def encrypt_file(file_path, output_path, fernet_key):
  42.     cipher_suite = Fernet(fernet_key)
  43.  
  44.     with open(file_path, "rb") as file:
  45.         file_data = file.read()
  46.  
  47.     encrypted_data = cipher_suite.encrypt(file_data)
  48.  
  49.     with open(output_path, "wb") as encrypted_file:
  50.         encrypted_file.write(encrypted_data)
  51.  
  52. # Decrypt a file using Fernet symmetric encryption
  53. def decrypt_file(file_path, output_path, fernet_key):
  54.     cipher_suite = Fernet(fernet_key)
  55.  
  56.     with open(file_path, "rb") as file:
  57.         encrypted_data = file.read()
  58.  
  59.     decrypted_data = cipher_suite.decrypt(encrypted_data)
  60.  
  61.     with open(output_path, "wb") as decrypted_file:
  62.         decrypted_file.write(decrypted_data)
  63.  
  64. # Sign a file with the RSA private key
  65. def sign_file(file_path, private_key):
  66.     with open(file_path, "rb") as file:
  67.         data = file.read()
  68.  
  69.     signature = private_key.sign(
  70.         data,
  71.         padding.PSS(
  72.             mgf=padding.MGF1(hashes.SHA256()),
  73.             salt_length=padding.PSS.MAX_LENGTH
  74.         ),
  75.         hashes.SHA256()
  76.     )
  77.  
  78.     with open(file_path + ".sig", "wb") as signature_file:
  79.         signature_file.write(signature)
  80.  
  81. # Verify the digital signature of a file
  82. def verify_signature(file_path, public_key):
  83.     with open(file_path, "rb") as file:
  84.         data = file.read()
  85.  
  86.     with open(file_path + ".sig", "rb") as signature_file:
  87.         signature = signature_file.read()
  88.  
  89.     try:
  90.         public_key.verify(
  91.             signature,
  92.             data,
  93.             padding.PSS(
  94.                 mgf=padding.MGF1(hashes.SHA256()),
  95.                 salt_length=padding.PSS.MAX_LENGTH
  96.             ),
  97.             hashes.SHA256()
  98.         )
  99.         return True
  100.     except Exception:
  101.         return False
  102.  
  103. # Calculate the hash of a file
  104. def calculate_hash(file_path):
  105.     sha256_hash = hashlib.sha256()
  106.     with open(file_path, "rb") as file:
  107.         while True:
  108.             data = file.read(65536)
  109.             if not data:
  110.                 break
  111.             sha256_hash.update(data)
  112.     return sha256_hash.hexdigest()
  113.  
  114. # Encrypt a Fernet key with RSA public key
  115. def encrypt_fernet_key(fernet_key, public_key):
  116.     encrypted_key = public_key.encrypt(
  117.         fernet_key,
  118.         padding.OAEP(
  119.             mgf=padding.MGF1(algorithm=hashes.SHA256()),
  120.             algorithm=hashes.SHA256(),
  121.             label=None,
  122.         ),
  123.     )
  124.     return encrypted_key
  125.  
  126. # Decrypt a Fernet key with RSA private key
  127. def decrypt_fernet_key(encrypted_key, private_key):
  128.     fernet_key = private_key.decrypt(
  129.         encrypted_key,
  130.         padding.OAEP(
  131.             mgf=padding.MGF1(algorithm=hashes.SHA256()),
  132.             algorithm=hashes.SHA256(),
  133.             label=None,
  134.         ),
  135.     )
  136.     return fernet_key
  137.  
  138. # Encrypt multiple files into a single archive
  139. def encrypt_multiple_files(file_paths, output_archive, fernet_key):
  140.     with zipfile.ZipFile(output_archive, 'w') as archive:
  141.         for file_path in file_paths:
  142.             archive.write(file_path, os.path.basename(file_path))
  143.    
  144.     # Encrypt the entire archive using Fernet
  145.     encrypt_file(output_archive, output_archive + ".enc", fernet_key)
  146.    
  147.     # Remove the unencrypted archive
  148.     os.remove(output_archive)
  149.  
  150. # Decrypt a single archive containing multiple files
  151. def decrypt_multiple_files(archive_path, output_dir, fernet_key):
  152.     # Decrypt the encrypted archive using Fernet
  153.     decrypt_file(archive_path, archive_path + ".dec", fernet_key)
  154.    
  155.     # Extract files from the decrypted archive
  156.     with zipfile.ZipFile(archive_path + ".dec", 'r') as archive:
  157.         archive.extractall(output_dir)
  158.    
  159.     # Remove the decrypted archive
  160.     os.remove(archive_path + ".dec")
  161.  
  162. # Main function
  163. def main():
  164.     # Step 1: Generate or load RSA keys
  165.     private_key, public_key = generate_rsa_keypair()
  166.     save_rsa_key(private_key, "private_key.pem", b'Passphrase123')  # Replace passphrase
  167.     save_rsa_key(public_key, "public_key.pem")
  168.  
  169.     # Step 2: Encrypt a file with Fernet
  170.     fernet_key = Fernet.generate_key()
  171.     encrypt_file("input.txt", "encrypted.fernet", fernet_key)
  172.  
  173.     # Step 3: Encrypt the Fernet key with the RSA public key
  174.     public_key = load_rsa_key("public_key.pem")
  175.     encrypted_fernet_key = encrypt_fernet_key(fernet_key, public_key)
  176.  
  177.     with open("encrypted_fernet_key", "wb") as fernet_key_file:
  178.         fernet_key_file.write(encrypted_fernet_key)
  179.  
  180.     # Step 4: Sign the file with the RSA private key
  181.     sign_file("input.txt", private_key)
  182.  
  183.     # Step 5: Verify the digital signature of the file
  184.     verified = verify_signature("input.txt", public_key)
  185.     if verified:
  186.         print("Digital signature is valid.")
  187.     else:
  188.         print("Digital signature is invalid or missing.")
  189.  
  190.     # Step 6: Calculate the hash of the encrypted Fernet key
  191.     encrypted_fernet_key_hash = calculate_hash("encrypted_fernet_key")
  192.     print(f"Hash of the encrypted Fernet key: {encrypted_fernet_key_hash}")
  193.  
  194.     # Step 7: Decrypt the Fernet key with the RSA private key
  195.     encrypted_fernet_key = open("encrypted_fernet_key", "rb").read()
  196.     private_key = load_rsa_key("private_key.pem", b'Passphrase123')  # Replace passphrase
  197.     fernet_key = decrypt_fernet_key(encrypted_fernet_key, private_key)
  198.  
  199.     # Step 8: Decrypt the file with the decrypted Fernet key
  200.     decrypt_file("encrypted.fernet", "decrypted.txt", fernet_key)
  201.     print("File encrypted and decrypted successfully.")
  202.  
  203.     # Step 9: Encrypt multiple files into a single archive
  204.     file_paths_to_encrypt = ["file1.txt", "file2.txt"]
  205.     output_archive = "multiple_files_archive.zip"
  206.     encrypt_multiple_files(file_paths_to_encrypt, output_archive, fernet_key)
  207.    
  208.     # Step 10: Decrypt a single archive containing multiple files
  209.     output_dir = "decrypted_files"
  210.     decrypt_multiple_files(output_archive, output_dir, fernet_key)
  211.    
  212.     print("Multiple files encrypted and decrypted successfully.")
  213.  
  214. if __name__ == "__main__":
  215.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement