I'm working on an app where users upload a file and the app processes it automatically for them. For data security, I want to encrypt these files. These files can be of varying sizes from small to very large (2MB to upwards of 30MB). I came across PyCrypto as the de facto encryption/decryption package. The files are read into io.BytesIO() after being processed and then a file is created from the bytes stream. I was wondering if it is possible to 'encrypt' the bytes stream and then create the file. So that when I read the file into io.Bytes(), I can decrypt it and serve the file to the user.
Asked
Active
Viewed 2,399 times
0
-
1Yes - have you tried it? – solarissmoke Feb 28 '20 at 06:27
-
No. I tried it for PyAesCrypt but the package doesn't have a great user base. So I'm skeptical. I've not tried it using PyCrypto as in I don't know how to proceed. Can you write out an example or a snippet? – Vaibhav Feb 28 '20 at 10:28
-
PyCrypto is abandoned and not works in Python 3.8, best candidate for this is pyca/cryptography. – frost-nzcr4 Feb 28 '20 at 10:31
1 Answers
1
PyCrypto is abandoned and not works in Python 3.8, so best candidate for this work is pyca/cryptography
but if you really need you can start with something like this:
from io import BytesIO
from Crypto import Random
from Crypto.Cipher import AES
payload = BytesIO(b"SomeData")
# Implement PKCS7 padding.
block_size = 16
length = payload.getbuffer().nbytes
to_pad = block_size - length % block_size
payload.seek(length)
payload.write((chr(to_pad) * to_pad).encode("utf8"))
payload.seek(0)
# Setup the cipher.
iv = Random.new().read(block_size)
cipher = AES.new(
"16-CHAR-LENGTH__", # Some secret.
mode=AES.MODE_CBC,
IV=iv,
)
encrypted = cipher.encrypt(payload.read())

frost-nzcr4
- 1,540
- 11
- 16
-
Hey, Thanks for the response. I haven't tried this yet. I'll let you know if this works for me as soon as possible! – Vaibhav Feb 28 '20 at 11:59