0% found this document useful (0 votes)
34 views1 page

Pip Install Cryptography Pycryptodome

The document provides a Python script that demonstrates how to encrypt and decrypt files using the cryptography library. It includes functions to generate a key, encrypt a file by appending '.enc' to its name, and decrypt it back to its original form. The script also saves the generated key to a file named 'secret.key'.

Uploaded by

Suvarn Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views1 page

Pip Install Cryptography Pycryptodome

The document provides a Python script that demonstrates how to encrypt and decrypt files using the cryptography library. It includes functions to generate a key, encrypt a file by appending '.enc' to its name, and decrypt it back to its original form. The script also saves the generated key to a file named 'secret.key'.

Uploaded by

Suvarn Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

pip install cryptography pycryptodome

from cryptography.fernet import Fernet

# Generate and save a key


key = Fernet.generate_key()
with open("secret.key", "wb") as key_file:
key_file.write(key)

def encrypt_file(file_path, key):


from cryptography.fernet import Fernet
with open(file_path, "rb") as file:
file_data = file.read()

fernet = Fernet(key)
encrypted_data = fernet.encrypt(file_data)

with open(file_path + ".enc", "wb") as file:


file.write(encrypted_data)

print("File encrypted successfully!")

def decrypt_file(file_path, key):


from cryptography.fernet import Fernet
with open(file_path, "rb") as file:
encrypted_data = file.read()

fernet = Fernet(key)
decrypted_data = fernet.decrypt(encrypted_data)

with open(file_path.replace(".enc", ""), "wb") as file:


file.write(decrypted_data)

print("File decrypted successfully!")

You might also like