Reputation: 26286
I have some data in a python program that I'd like to encrypt before writing to a file with a password, and then read it and decrypt it before using it. I'm looking for some secure symmetric algorithm that can encrypt and decrypt against a password.
This question shows a non-secure way and suggests using libsodium. Since I'm using Python, I found pysodium. It seems to have tons of functions mapped from libsodium, but I don't know how to simply encrypt/decrypt data against password.
My problem is that it looks like all encryption algorithms use keys. I don't want to use keys. I want to only use a password. Just like what I do in the terminal:
To encrypt:
$ cat data | openssl aes-256-cbc -salt | dd of=output.des3
To decrypt:
$ dd if=output.des3 | openssl aes-256-cbc -d -salt
Is it possible to do this with pysodium (in a cross-platform way, so please don't suggest using a system call)?
Upvotes: 3
Views: 2639
Reputation: 26286
So my question reduced to: "How can I encrypt data against a password in Python". I gave up on pysodium due to the lack of documentation. I used cryptography
and argon2
packages to write my own encryption algorithm (it's not my own crypto algorithm, I know Rule No. 1 in crypto; it's just the procedure to utilize what's already there). So here are my functions:
import cryptography.fernet
import argon2
import base64
def encrypt_data(data_bytes, password, salt):
password_hash = argon2.argon2_hash(password=password, salt=salt)
encoded_hash = base64.urlsafe_b64encode(password_hash[:32])
encryptor = cryptography.fernet.Fernet(encoded_hash)
return encryptor.encrypt(data_bytes)
def decrypt_data(cipher_bytes, password, salt):
password_hash = argon2.argon2_hash(password=password, salt=salt)
encoded_hash = base64.urlsafe_b64encode(password_hash[:32])
decryptor = cryptography.fernet.Fernet(encoded_hash)
return decryptor.decrypt(cipher_bytes)
And here's an example on how to use them:
cipher = encrypt_data("Hi Dude, Don't tell anyone I said Hi!".encode(), "SecretPassword", "SaltySaltySalt")
decrypted = decrypt_data(cipher, "SecretPassword", "SaltySaltySalt")
print(cipher)
print(decrypted.decode())
Remember that encryption is for bytes only; not for strings. This is why I'm using encode
/decode
.
Why argon2? Because it's a memory hard algorithm that's very hard to break with GPUs and ASICs (yes, I'm a cryptocurrency fan).
Why Fernet? Because it uses AES CBC, which seems to be secure enough; besides, it's really easy to use (which is exactly what I need... I'm not a cryptographer, so I need a black-box to use).
Disclaimer: Please be aware that I'm not a cryptographer. I'm just a programmer. Please feel free to critique my way of encrypting and decrypting, and please feel free to add your contribution to make this better.
Upvotes: 5