I need to encrypt the file.

The simplest thing that occurred to me was to simply read the file, and write it, for example, into a variable of type string. Then encrypt the data in this variable. Clear the file, and write the modified data from this variable there.

But the problem is that the file can significantly exceed the size of RAM.

Tell me, please, how is it customary to work with large files (read, write)? If anyone can throw off the code in C ++, it will be generally cool.

  • 6
    and why it is impossible to read 4 kilobytes, encrypt, write, then the next 4k. The main thing is to process the residue correctly. Most encryption algorithms work well with this - it is called "stream encryption". The only thing that some algorithms encrypt these pieces (they are called blocks) independently (that is, the same blocks will be encrypted with the same sequences) and the associated encryption - when some block remains after the block is encrypted, which is used to encrypt the next one. - KoVadim

1 answer 1

@vvtvvtvvt , it all depends on the encryption method. For most cases, the method proposed by @KoVadim is absolutely suitable. Or you can not use buffering explicitly, it is already “embedded” in the library functions for working with files.

A simple example of such a program in C. (You can train yourself and translate yourself to C ++ streams).

// Простое потоковое шифрование файла любой длины на том же месте // ./a.out filename [password] // для расшифровки запустить еще раз с тем же password #include <stdio.h> #include <string.h> int main (int ac, char *av[]) { if (ac < 2) { fprintf (stderr, "Usage: %s filename [password]\n", av[0]); return 1; } char *fname, *pass; fname = av[1]; pass = av[2] ? av[2] : fname; FILE *in = fopen(fname, "r"), *out = fopen(fname, "r+"); // чтение и запись БЕЗ УРЕЗАНИЯ файла if (!in || !out) { perror(fname); return 2; } rewind(out); // требуется для перевода файла в режим записи int c, i = 0, l = strlen(pass); while ((c = fgetc(in)) != EOF) { c ^= pass[i]; fputc(c, out); i = (++i) % l; // циклически перебираем символы pass } return fclose(out) + fclose(in); } 

By the way, g ++ also compiles it.

If you wish, you can complicate (somewhat strengthen) such an algorithm. For example, you can calculate HASH (pass) and encrypt it by recalculating HASH (previous HASH) each time you read N characters (say, HASH size).