

Note that in general, you should not directly encrypt data with RSA. For large files, it would be better to encrypt chunk by chunk you can encrypt as little as a block at a time (16 bytes for AES), but you need a better crypto library for that. Unfortunately, it only supports all-at-once encryption. The API of the block cipher is described in PEP 272. Here, since the key is only ever used once, you can use a known IV. Normally, it's sent alongside the data in cleartext.

It needs to be unique per key per message. The iv is an initialization vector for the CBC mode of operation. Output.write(aes_engine.encrypt(input.read())) # Encrypt the file (see below regarding iv)Īes_engine = AES.new(secret_key, AES.MODE_CBC, iv) # Write out the encrypted secret key, preceded by a length indication Padding += '\0' * (plaintext_length - len(padding) - len(secret_key))Įncrypted_secret_key = rsa.encrypt(padding + secret_key, None) So here's a sketch of how encryption can look like (warning, untested code, typed directly in the browser): import os Sign the digest of the file with the private key and store that alongside the file. To sign a file, compute a cryptographic digest (e.g.Store the data encrypted with this cipher, and store the secret key encrypted with the public key alongside the encrypted payload. To encrypt a file, randomly generate a secret key for a block or stream cipher (e.g.The usual practice is to use other methods to reduce the asymmetric problem to one where the security is provided by a shared key, then use public-key cryptography to protect that shared key. It is slow, and can be hard to use right.

Public-key cryptography is usually used for small amounts of data only. I heard about Mcrypt and OpenSSL, but I don't know if they can encrypt files.

So my question is : are there any better methods for using Private/ Public key encryption ON FILES ? Open('encrypted_file.ext', 'wb').write(encrypted) # when i explode the string back for decryption. # I hope the \r\r\r sequence won't appear in the encrypted result, # RSA encryption returns a tuple containing 1 string, so i fetch the string. # Encrypt with RSA and append the result to list. This is the code so far: from Crypto.PublicKey import RSAįile_to_encrypt = open('my_file.ext', 'rb').read() I know it's somewhat wrong, first of all because RSA is very slow and second because P圜rypto RSA can only encrypt 128 characters, so you have to explode the file in 128 characters chunks. I'm implementing file encryption with RSA, using P圜rypto.
