Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

openssl aes256 encryption of a file

I'd like to encrypt a file with aes256 using OpenSSL with C. I did find a pretty nice example here.

Should I first read the whole file into a memory buffer and than do the aes256, or should I do it partial with a ~16K buffer?

Any snippets or hints?

like image 760
Jonas Schnelli Avatar asked Oct 18 '11 19:10

Jonas Schnelli


2 Answers

Loading the whole file in a buffer can get inefficient to impossible on larger files - do this only if all your files are below some size limit.

OpenSSL's EVP API (which is also used by the example you linked) has an EVP_EncryptUpdate function, which can be called multiple times, each time providing some more bytes to encrypt. Use this in a loop together with reading in the plaintext from a file into a buffer, and writing out the ciphertext to another file (or the same one). (Analogously for decryption.)

Of course, instead of inventing a new file format (which you are effectively doing here), think about implementing the OpenPGP Message format (RFC 4880). There are less chances to make mistakes which might destroy your security – and as an added bonus, if your program somehow ceases to work, your users can always use the standard tools (PGP or GnuPG) to decrypt the file.

like image 103
Paŭlo Ebermann Avatar answered Oct 08 '22 22:10

Paŭlo Ebermann


It's better to reuse a fixed buffer, unless you know you'll always process small files - but I don't think that fits your backup files definition.

I said better in a non-cryptographic way :-) There won't be any difference at the end (for the encrypted file) but your computer might not like (or even be able) to load several MB (or GB) into memory.

Crypto-wise the operations are done in block, for AES it's 128 bits (16 bytes). So, for simplicity, you better use a multiple of 16 bytes for your buffer. Otherwise the choice is yours. I would suggest between 4kb to 16kb buffers but, to be honest, I would test several values.

like image 36
poupou Avatar answered Oct 09 '22 00:10

poupou