I want to encrypt some small text files so I can put them online, in non-restricted access (not the best idea, but it's cheap and simple). I know I should use something like Truecrypt instead of this, but I'm looking for something lighter and simple.
import base64
import os
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from sys import argv
if len(argv)<3:
exit('please provide a password')
exit()
# password = b"password"
password = argv[2].encode()
salt = os.urandom(16)
salt = b'\x03>\x8d\xd9x\x8d\xdcR\xc9\x1b-\x9c\x86\xc7\x83\x8c'
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
backend=default_backend()
)
key = base64.urlsafe_b64encode(kdf.derive(password))
# print(key)
f = Fernet(key)
# print(token)
# print(f.decrypt(token))
# print(salt)
if "encrypt" in argv:
plain_src = open("plain.nogit.txt", encoding='utf8')
crypted = open("crypted.nogit.txt",'w')
token = f.encrypt(plain_src.read().encode())
plain_src.read().encode()
# print(repr(token))
crypted.write(repr(token))
elif "decrypt" in argv:
plain_src = open("plain.decrypted.nogit.txt",'w', encoding='utf8')
crypted = open("crypted.nogit.txt")
token = eval(crypted.read())
plain_src.write(f.decrypt(token).decode())
if open("plain.decrypted.nogit.txt", encoding='utf8').read() == open("plain.nogit.txt", encoding='utf8').read():
print('same content')
else:
print('different content')
else:
exit('provide either 1 or 2 args')
How secure is this? I'm aware that this would leave the password in the shell history (which can be deleted and cleared), but I just want to ask if this the right way to encrypt some simple text data. My goal here is to have best ratio security/simplicity. What would you change? Any advice?