Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import zipfile
- from cryptography.hazmat.primitives import serialization, hashes
- from cryptography.hazmat.primitives.asymmetric import rsa, padding
- from cryptography.fernet import Fernet
- import hashlib
- # Generate or load RSA keys
- def generate_rsa_keypair(key_size=4096):
- private_key = rsa.generate_private_key(
- public_exponent=65537,
- key_size=key_size
- )
- return private_key, private_key.public_key()
- def save_rsa_key(key, filename, passphrase=None):
- with open(filename, "wb") as key_file:
- if passphrase:
- key_pem = key.private_bytes(
- encoding=serialization.Encoding.PEM,
- format=serialization.PrivateFormat.PKCS8,
- encryption_algorithm=serialization.BestAvailableEncryption(passphrase),
- )
- else:
- key_pem = key.private_bytes(
- encoding=serialization.Encoding.PEM,
- format=serialization.PrivateFormat.PKCS8,
- encryption_algorithm=serialization.NoEncryption()
- )
- key_file.write(key_pem)
- def load_rsa_key(filename, passphrase=None):
- with open(filename, "rb") as key_file:
- key_pem = key_file.read()
- if passphrase:
- return serialization.load_pem_private_key(key_pem, passphrase)
- else:
- return serialization.load_pem_private_key(key_pem, None)
- # Encrypt a file using Fernet symmetric encryption
- def encrypt_file(file_path, output_path, fernet_key):
- cipher_suite = Fernet(fernet_key)
- with open(file_path, "rb") as file:
- file_data = file.read()
- encrypted_data = cipher_suite.encrypt(file_data)
- with open(output_path, "wb") as encrypted_file:
- encrypted_file.write(encrypted_data)
- # Decrypt a file using Fernet symmetric encryption
- def decrypt_file(file_path, output_path, fernet_key):
- cipher_suite = Fernet(fernet_key)
- with open(file_path, "rb") as file:
- encrypted_data = file.read()
- decrypted_data = cipher_suite.decrypt(encrypted_data)
- with open(output_path, "wb") as decrypted_file:
- decrypted_file.write(decrypted_data)
- # Sign a file with the RSA private key
- def sign_file(file_path, private_key):
- with open(file_path, "rb") as file:
- data = file.read()
- signature = private_key.sign(
- data,
- padding.PSS(
- mgf=padding.MGF1(hashes.SHA256()),
- salt_length=padding.PSS.MAX_LENGTH
- ),
- hashes.SHA256()
- )
- with open(file_path + ".sig", "wb") as signature_file:
- signature_file.write(signature)
- # Verify the digital signature of a file
- def verify_signature(file_path, public_key):
- with open(file_path, "rb") as file:
- data = file.read()
- with open(file_path + ".sig", "rb") as signature_file:
- signature = signature_file.read()
- try:
- public_key.verify(
- signature,
- data,
- padding.PSS(
- mgf=padding.MGF1(hashes.SHA256()),
- salt_length=padding.PSS.MAX_LENGTH
- ),
- hashes.SHA256()
- )
- return True
- except Exception:
- return False
- # Calculate the hash of a file
- def calculate_hash(file_path):
- sha256_hash = hashlib.sha256()
- with open(file_path, "rb") as file:
- while True:
- data = file.read(65536)
- if not data:
- break
- sha256_hash.update(data)
- return sha256_hash.hexdigest()
- # Encrypt a Fernet key with RSA public key
- def encrypt_fernet_key(fernet_key, public_key):
- encrypted_key = public_key.encrypt(
- fernet_key,
- padding.OAEP(
- mgf=padding.MGF1(algorithm=hashes.SHA256()),
- algorithm=hashes.SHA256(),
- label=None,
- ),
- )
- return encrypted_key
- # Decrypt a Fernet key with RSA private key
- def decrypt_fernet_key(encrypted_key, private_key):
- fernet_key = private_key.decrypt(
- encrypted_key,
- padding.OAEP(
- mgf=padding.MGF1(algorithm=hashes.SHA256()),
- algorithm=hashes.SHA256(),
- label=None,
- ),
- )
- return fernet_key
- # Encrypt multiple files into a single archive
- def encrypt_multiple_files(file_paths, output_archive, fernet_key):
- with zipfile.ZipFile(output_archive, 'w') as archive:
- for file_path in file_paths:
- archive.write(file_path, os.path.basename(file_path))
- # Encrypt the entire archive using Fernet
- encrypt_file(output_archive, output_archive + ".enc", fernet_key)
- # Remove the unencrypted archive
- os.remove(output_archive)
- # Decrypt a single archive containing multiple files
- def decrypt_multiple_files(archive_path, output_dir, fernet_key):
- # Decrypt the encrypted archive using Fernet
- decrypt_file(archive_path, archive_path + ".dec", fernet_key)
- # Extract files from the decrypted archive
- with zipfile.ZipFile(archive_path + ".dec", 'r') as archive:
- archive.extractall(output_dir)
- # Remove the decrypted archive
- os.remove(archive_path + ".dec")
- # Main function
- def main():
- # Step 1: Generate or load RSA keys
- private_key, public_key = generate_rsa_keypair()
- save_rsa_key(private_key, "private_key.pem", b'Passphrase123') # Replace passphrase
- save_rsa_key(public_key, "public_key.pem")
- # Step 2: Encrypt a file with Fernet
- fernet_key = Fernet.generate_key()
- encrypt_file("input.txt", "encrypted.fernet", fernet_key)
- # Step 3: Encrypt the Fernet key with the RSA public key
- public_key = load_rsa_key("public_key.pem")
- encrypted_fernet_key = encrypt_fernet_key(fernet_key, public_key)
- with open("encrypted_fernet_key", "wb") as fernet_key_file:
- fernet_key_file.write(encrypted_fernet_key)
- # Step 4: Sign the file with the RSA private key
- sign_file("input.txt", private_key)
- # Step 5: Verify the digital signature of the file
- verified = verify_signature("input.txt", public_key)
- if verified:
- print("Digital signature is valid.")
- else:
- print("Digital signature is invalid or missing.")
- # Step 6: Calculate the hash of the encrypted Fernet key
- encrypted_fernet_key_hash = calculate_hash("encrypted_fernet_key")
- print(f"Hash of the encrypted Fernet key: {encrypted_fernet_key_hash}")
- # Step 7: Decrypt the Fernet key with the RSA private key
- encrypted_fernet_key = open("encrypted_fernet_key", "rb").read()
- private_key = load_rsa_key("private_key.pem", b'Passphrase123') # Replace passphrase
- fernet_key = decrypt_fernet_key(encrypted_fernet_key, private_key)
- # Step 8: Decrypt the file with the decrypted Fernet key
- decrypt_file("encrypted.fernet", "decrypted.txt", fernet_key)
- print("File encrypted and decrypted successfully.")
- # Step 9: Encrypt multiple files into a single archive
- file_paths_to_encrypt = ["file1.txt", "file2.txt"]
- output_archive = "multiple_files_archive.zip"
- encrypt_multiple_files(file_paths_to_encrypt, output_archive, fernet_key)
- # Step 10: Decrypt a single archive containing multiple files
- output_dir = "decrypted_files"
- decrypt_multiple_files(output_archive, output_dir, fernet_key)
- print("Multiple files encrypted and decrypted successfully.")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement