APL/DEV 4.4/TP02/Ex1/spn-decrypt-file.c
2023-03-24 16:04:40 +01:00

61 lines
1.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include "spn.h"
int main(int argc, char const *argv[])
{
if (argc < 6) {
printf("Usage: %s <key> <subst> <perm> <decoded> <coded>\n", argv[0]);
return 1;
}
unsigned short key;
unsigned char tempPerm[8], perm[8], tempSubst[16], subst[16];
FILE* keyFile = fopen(argv[1], "r");
if (fread(&key, 2, 1, keyFile) != 1) {
printf("Unable to read key file\n");
return 1;
} else fclose(keyFile);
FILE* substFile = fopen(argv[2], "r");
if (fread(&tempSubst, 1, 16, substFile) != 16) {
printf("Unable to read subst file\n");
return 1;
} else fclose(substFile);
for (int i = 0; i < 16; i++) {
subst[tempSubst[i]] = i;
}
FILE* permFile = fopen(argv[3], "r");
if (fread(&tempPerm, 1, 8, permFile) != 8) {
printf("Unable to read permutation file\n");
return 1;
} else fclose(permFile);
for (int i = 0; i < 8; i++) {
perm[tempPerm[i]] = i;
}
FILE* decoded = fopen(argv[4], "r");
FILE* encoded = fopen(argv[5], "w");
if (!decoded || !encoded) {
printf("Unable to read/write content into files\n");
return 1;
}
char w;
while (fread(&w, 1, 1, decoded)) {
w = decrypt(w, key, perm, subst);
if (!fwrite(&w, 1, 1, encoded)) {
printf("Error during writing\n");
return 1;
}
}
return 0;
}