I have to write a program to decrypt a bin file, as a result of decryption i have a txt file with numbers. However, I need to have a file with letters to read this file. The encryption key is 5. How can I make it produce a text after decryption?
#include <stdio.h>
#include <string.h>
#define MAX 256
int main() {
FILE *fp1, *fp2;
int key, val, ch, i = 0;
char filename[MAX], temp[] = "temp.txt";
/* get the file name from the user */
printf("Enter your file name:");
scanf("%s", filename);
/* open the given file in read mode */
fp1 = fopen(filename, "r");
/* error handling */
if (!fp1) {
printf("Unable to open the input file!!\n");
return 0;
}
/* open the temporary file in write mode */
fp2 = fopen(temp, "w");
/* error handling */
if (!fp2) {
printf("Unable to open the temporary file!!\n");
return 0;
}
/* get the key from the user to create cipher */
printf("Enter the key to create cipher text:");
scanf("%d", &key);
/* converting plain text to cipher text */
while ((ch = fgetc(fp1)) != EOF) {
/* adding key to the ascii value of the fetched char */
val = ch + key;
fprintf(fp2, "%d ", val);
i++;
if (i % 10 == 0) {
fprintf(fp2, "\n");
}
}
/* closing all opened files */
fclose(fp1);
fclose(fp2);
/* open the file containint cipher text in read mode */
fp2 = fopen(temp, "r");
/* printing the cipher text */
printf("\nCipher text for the given plain text:\n");
while (!feof(fp2)) {
fscanf(fp2, "%d", &ch);
if (!feof(fp2)) {
printf("%c", ch);
}
}
/* moving the file pointer to the start of file */
rewind(fp2);
/*
* converting the cipher text to plain
* text and printing it to console
*/
printf("\n\nConverting the cipher text to plain text:\n");
while (!feof(fp2)) {
fscanf(fp2, "%d", &ch);
if (!feof(fp2)) {
val = ch - key;
printf("%c", val);
}
}
printf("\n");
/* close all opened files */
fclose(fp2);
return 0;
printf("\n");
}
If I use key 8234 it should produce a text with instructions, but I get this:
8313 8356 8344 8346 8321 8325 8322 8328 8286 8313 8471 8440 8471 8464 8471 8458 8471 8435 8286 8326 8308 8324 8308 8387 8374 8382 8286 8336 8336 8323 8352 8377 8386 8379 8392 8380 8308 8327 8308 8324 8308 8358 8323 8346 8381 8384 8392 8377 8390 8323 8346 8384 8373 8392 8377 8344 8377 8375 8387 8376 8377 8338 8338 8286 8391 8392 8390 8377 8373 8385 8286 8396 8432 8257 8303 8477 8446 8319 8463 8389 8403 8466 8470 8255 8468 8389 8312 8425 8410 8386 8324 8282 8355 8315 8420 8241 8351 8290 8376 8293 8454 8479 8276 8309 8285 8248 8385 8262 8271 8445 8318 8353 8441 8386 8349 8458 8259 8311 8463 8388 8461 8338 8385 8457 8410 8430 8347 8365 8305 8265 8245 8339 8307 8275 8338 8316 8272 8251 8457 8333 8408 8489 8304 8402 8274 8479 8475 8307 8402 8393 8268 8363 8304 8337 8366 8281 8332 8442 8418 8474 8406 8410 8471 8483 8403 8271 8460 8402 8403 8300 8281 8347 8399 8284 8346 8305 8245 8260 8273 8251 8471 8451 8467 8264 8341 8271 8471 8267 8371 8275 8396 8358 8270 8288 8315 8377 8482 8435 8250 8440.....