Home > other >  How to read 16 bytes from a file at a time and store them into an array
How to read 16 bytes from a file at a time and store them into an array

Time:08-07

I am trying to read 16 bytes at a time from a file, and every 16 bytes must be encrypted and written to an output file. Assuming the encryption function shift_encrypt is working, how can I apply it to 16 bytes at time. Currently I am attempting to store the bytes in an array plaintext but it is not working

void encryption(char filename[MAX_PATH_LEN], char password[CIPHER_BLOCK_SIZE   1]) {
    
    char output[256];
    snprintf(output, sizeof(output), "%s.ecb", filename);
    FILE *output_stream = fopen(output, "wb");
   
    if (output_stream == NULL) {
        perror(output);
    }

    FILE *input_stream = fopen(filename, "rb");
    if (input_stream == NULL) {
        perror(filename);
    } 

    char plaintext[17];
    while (fread(plaintext, 16, 1, input_stream) != 0) {
        fwrite(shift_encrypt(plaintext, password), 16, 1, output_stream);
    }

    fclose(output_stream);
}

CodePudding user response:

How to read 16 bytes from a file at a time and store them into an array (?)

Code is doing that part just fine.

Assuming it is a string, would the code I have work? Because I am getting a stack buffer overflow error when I run it. For example I am reading from a text file containing 'AAAABBBBCCCCDDDDE', and the password is 'passwordpassword'

The assumption is incorrect.

Consider why code is plaintext[] size 17, yet never assigned plaintext[16] and only reading 16. Code is not reading 'AAAABBBBCCCCDDDDE', but only 'AAAABBBBCCCCDDDD' and the last (17th) character of plaintext[] is never assigned.

Try char plaintext[17]; = { 0 }; to initialize the array. Then character plaintext[16] will be a null character and after a successful fread(plaintext, 16, 1, input_stream), plainttext[] will be a string suitable for shift_encrypt(plaintext, password).

  • Related