|
| 1 | +# Import the library we install in step 1 |
| 2 | +import cryptography |
| 3 | +import base64 |
| 4 | +import os |
| 5 | +from cryptography.hazmat.backends import default_backend |
| 6 | +from cryptography.hazmat.primitives import hashes |
| 7 | +from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC |
| 8 | +from cryptography.fernet import Fernet |
| 9 | + |
| 10 | +SALT = b'SOME_RANDOM_SALT' |
| 11 | + |
| 12 | +def Encrypter(filename, password): |
| 13 | + password = password.encode() |
| 14 | + |
| 15 | + kdf = PBKDF2HMAC( |
| 16 | + algorithm=hashes.SHA512(), |
| 17 | + length=32, |
| 18 | + salt=SALT, |
| 19 | + iterations=100000, |
| 20 | + backend=default_backend() |
| 21 | + ) |
| 22 | + |
| 23 | + key = base64.urlsafe_b64encode(kdf.derive(password)) |
| 24 | + fernet = Fernet(key) |
| 25 | + |
| 26 | + print('Opening file: ' + filename) |
| 27 | + with open(filename, 'rb') as f: |
| 28 | + data = f.read() |
| 29 | + |
| 30 | + print('Encrypting...') |
| 31 | + encryptedData = fernet.encrypt(data) |
| 32 | + |
| 33 | + print('Saving encrypted: ' + filename + '.enc') |
| 34 | + with open(filename + '.enc', 'wb') as f: |
| 35 | + f.write(encryptedData) |
| 36 | + |
| 37 | + print("----") |
| 38 | + print("DONE") |
| 39 | + |
| 40 | +def Decrypter(filename, password): |
| 41 | + password = password.encode() |
| 42 | + |
| 43 | + kdf = PBKDF2HMAC( |
| 44 | + algorithm=hashes.SHA512(), |
| 45 | + length=32, |
| 46 | + salt=SALT, |
| 47 | + iterations=100000, |
| 48 | + backend=default_backend() |
| 49 | + ) |
| 50 | + |
| 51 | + key = base64.urlsafe_b64encode(kdf.derive(password)) |
| 52 | + fernet = Fernet(key) |
| 53 | + |
| 54 | + # Open file |
| 55 | + print('Opening encrypted file: ' + filename) |
| 56 | + with open(filename, 'rb') as f: |
| 57 | + encryptedFileData = f.read() |
| 58 | + |
| 59 | + # Decrypt |
| 60 | + print('Decrypting file...') |
| 61 | + decryptedFileData = fernet.decrypt(encryptedFileData) |
| 62 | + |
| 63 | + # Let's remove the .enc that we added when encrypting |
| 64 | + decryptedFilename = filename.replace('.enc','') |
| 65 | + # Let's add dec prefix just in case the old unecrypted file |
| 66 | + # is still there. |
| 67 | + decryptedFilename = 'dec_' + decryptedFilename |
| 68 | + |
| 69 | + print('Saving decrypted file data: ' + decryptedFilename) |
| 70 | + with open(decryptedFilename, 'wb') as f: |
| 71 | + f.write(decryptedFileData) |
| 72 | + |
| 73 | + print("----") |
| 74 | + print("DONE") |
0 commit comments