[c] Implemented the chacha20_int_attck.c
This commit is contained in:
parent
53ba1d56ba
commit
c498c1d09a
1 changed files with 80 additions and 0 deletions
80
TPs/TP02/c/src/chacha20_int_attck.c
Normal file
80
TPs/TP02/c/src/chacha20_int_attck.c
Normal file
|
@ -0,0 +1,80 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
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 <fctxt> <pos> <ptxtAtPos> <newPtxtAtPos>\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
attack(argv[1], atoi(argv[2]), argv[3], argv[4]);
|
||||
return 0;
|
||||
}
|
Loading…
Reference in a new issue