From c498c1d09ad99605ac34d4236102e4434937bb5b Mon Sep 17 00:00:00 2001 From: afonsofrancof Date: Thu, 22 Feb 2024 02:46:32 +0000 Subject: [PATCH] [c] Implemented the chacha20_int_attck.c --- TPs/TP02/c/src/chacha20_int_attck.c | 80 +++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 TPs/TP02/c/src/chacha20_int_attck.c diff --git a/TPs/TP02/c/src/chacha20_int_attck.c b/TPs/TP02/c/src/chacha20_int_attck.c new file mode 100644 index 0000000..fd4ce1c --- /dev/null +++ b/TPs/TP02/c/src/chacha20_int_attck.c @@ -0,0 +1,80 @@ +#include +#include +#include + +void attack(char *fctxt, int pos, char *plain_at_pos, char *new_plain_at_pos) { + FILE *f = fopen(fctxt, "rb"); + if (f == NULL) { + fprintf(stderr, "Error opening file\n"); + return; + } + + // Get the size of the file + fseek(f, 0, SEEK_END); + unsigned long fsize = ftell(f); + rewind(f); + + // Allocate memory for the file + unsigned char *nonce_and_ciphertext = malloc(fsize * sizeof(unsigned char)); + if (nonce_and_ciphertext == NULL) { + printf("Error allocating memory\n"); + fclose(f); + return; + } + + if (fread(nonce_and_ciphertext, 1, fsize, f) != fsize) { + printf("Error reading file\n"); + fclose(f); + free(nonce_and_ciphertext); + return; + } + fclose(f); + + unsigned char *ciphertext = malloc((fsize * sizeof(unsigned char)) - 16); + memcpy(ciphertext, nonce_and_ciphertext + 16, fsize - 16); + + int plain_at_pos_len = strlen(plain_at_pos); + // Modify the ciphertext + for (int i = 0; i < plain_at_pos_len; i++) { + ciphertext[pos + i] = ciphertext[pos + i] ^ (plain_at_pos[i] ^ new_plain_at_pos[i]); + } + memcpy(nonce_and_ciphertext + 16, ciphertext, fsize - 16); + + // Write the modified ciphertext to the file + char *output_file = malloc(strlen(fctxt) + 7); + strcpy(output_file, fctxt); + strcat(output_file, ".attck"); + FILE *foutput = fopen(output_file, "wb"); + + if (foutput == NULL) { + fprintf(stderr, "Error opening output file\n"); + fclose(f); + free(ciphertext); + free(output_file); + return; + } + + if (fwrite(nonce_and_ciphertext, 1, fsize, foutput) != fsize) { + fprintf(stderr, "Error writing to file\n"); + fclose(f); + fclose(foutput); + free(ciphertext); + free(output_file); + return; + } + + fclose(f); + fclose(foutput); + free(ciphertext); + free(output_file); +} + +int main(int argc, char *argv[]) { + if (argc != 5) { + fprintf(stderr, "Usage: %s \n", argv[0]); + return 1; + } + + attack(argv[1], atoi(argv[2]), argv[3], argv[4]); + return 0; +}