I'm using libgcrypt to encrypt and decrypt files. When I take in the proper amount of bytes using fread, I need to pad it with 16-n bytes in order for it to properly be encrypted by gcry_cipher_encrypt. Upon decryption however, the null bytes/padding is still present. Is there any way to read and write in 16 byte blocks and still strip the padding at the end?
#include <stdio.h>
#include <gcrypt.h>
#define algo GCRY_CIPHER_AES128
#define mode GCRY_CIPHER_MODE_CBC
#define KEY_LENGTH 16
#define BLOCK_LENGTH 16
int main(){
    char IV[16];
    char *encBuffer = NULL;
    FILE *in, *out, *reopen;
    char *key = "A key goes here!";
    gcry_cipher_hd_t handle;
    int bufSize = 16, bytes;
    memset(IV, 0, 16);
    encBuffer = malloc(bufSize);
    in = fopen("in.txt", "r");
    out = fopen("out.txt", "w");
    gcry_cipher_open(&handle, algo, mode, 0);
    gcry_cipher_setkey(handle, key, KEY_LENGTH);
    gcry_cipher_setiv(handle, IV, BLOCK_LENGTH);
    while(1){
        bytes = fread(encBuffer, 1, bufSize, in);
        if (!bytes) break;
        while(bytes < bufSize)
            encBuffer[bytes++] = 0x0;
        gcry_cipher_encrypt(handle, encBuffer, bufSize, NULL, 0);
        bytes = fwrite(encBuffer, 1, bufSize, out);
    }
    gcry_cipher_close(handle);
    fclose(in);
    fclose(out);
    gcry_cipher_open(&handle, algo, mode, 0);
    gcry_cipher_setkey(handle, key, KEY_LENGTH);
    gcry_cipher_setiv(handle, IV, BLOCK_LENGTH);
    reopen = fopen("out.txt", "r");
    out = fopen("decoded.txt", "w");
    while(1){
        bytes = fread(encBuffer, 1, bufSize, reopen);
        if (!bytes) break;
        gcry_cipher_decrypt(handle, encBuffer, bufSize, NULL, 0);
        bytes = fwrite(encBuffer, 1, bufSize, out);
    }
    gcry_cipher_close(handle);
    free(encBuffer);
    return 0;
}
 
     
     
     
    