Created
October 16, 2020 11:37
-
-
Save avsilva/69007bbe857b87a7ae6fed069e88264d to your computer and use it in GitHub Desktop.
python encrypt/decrypt files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import base64 | |
import cryptography | |
from cryptography.fernet import Fernet, InvalidToken | |
from cryptography.hazmat.backends import default_backend | |
from cryptography.hazmat.primitives import hashes | |
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC | |
def generate_key(): | |
password_provided = input("password:") | |
password = password_provided.encode() # Convert to type bytes | |
salt = b'_salt' # CHANGE THIS - recommend using a key from os.urandom(16), must be of type bytes | |
kdf = PBKDF2HMAC( | |
algorithm=hashes.SHA256(), | |
length=32, | |
salt=salt, | |
iterations=100000, | |
backend=default_backend() | |
) | |
key = base64.urlsafe_b64encode(kdf.derive(password)) # Can only use kdf once | |
return key | |
filename = 'xpto' | |
input_file = './output/'+filename+'.pptx' | |
output_encrypt_file = './encrypt/'+filename+'.encrypted' | |
key = generate_key() | |
#filekey = open('key.key', 'wb') # Open the file as wb to write bytes | |
#filekey.write(key) # The key is type bytes still | |
#filekey.close() | |
## ENCRYPT ## | |
with open(input_file, 'rb') as f: | |
data = f.read() # Read the bytes of the input file | |
fernet = Fernet(key) | |
encrypted = fernet.encrypt(data) | |
fernet = Fernet(key) | |
encrypted = fernet.encrypt(data) | |
with open(output_encrypt_file, 'wb') as f: | |
f.write(encrypted) # Write the encrypted bytes to the output file | |
## DECRYPT ## | |
output_decrypt_file = './encrypt/'+filename+'.pptx' | |
key = generate_key() | |
fernet = Fernet(key) | |
with open(output_encrypt_file, 'rb') as f: | |
data = f.read() # Read the bytes of the encrypted file | |
try: | |
decrypted = fernet.decrypt(data) | |
with open(output_decrypt_file, 'wb') as f: | |
f.write(decrypted) # Write the decrypted bytes to the output file | |
# Note: You can delete input_file here if you want | |
except InvalidToken as e: | |
print("Invalid Key - Unsuccessfully decrypted") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment