c - Strip AES padding during fread/fwrite -


i'm using libgcrypt encrypt , decrypt files. when take in proper amount of bytes using fread, need pad 16-n bytes in order encrypted gcry_cipher_encrypt. upon decryption however, null bytes/padding still present. there way read , write in 16 byte blocks , still strip padding @ 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; } 

block ciphers have many modes of operation. require input data length mmultiple of block size, , require plaintext padding; don't. see more here.

if must use mode requires padding, must save plaintext length along encrypted data. simplest way write in additional block in end (encrypt block too!). there other, more sophisticated schemes, don't require addimg block; see this.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

python - pip wont install .WHL files -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -