Wednesday, March 15, 2023

C program to decrypt a text file using Caesar Cipher

Caesar Cipher File Decryptor


This C program will decrypt a given text file into plain text file using Caesar Cipher cryptographic algorithm.


#include <stdio.h>
#define MAX_FILE_SIZE 1000

//function to decrypt message based on given key
void decrypt(char *message, int key) {
    char ch;
    int i;
    for(i = 0; message[i] != '\0'; ++i){
        ch = message[i];
        if(ch >= 'a' && ch <= 'z'){
            ch = ch - key;
            if(ch < 'a'){
                ch = ch + 'z' - 'a' + 1;
            }
            message[i] = ch;
        }
        else if(ch >= 'A' && ch <= 'Z'){
            ch = ch - key;
            if(ch < 'A'){
                ch = ch + 'Z' - 'A' + 1;
            }
            message[i] = ch;
        }
    }
}

int main() {
    FILE *fileIn, *fileOut;
    char message[MAX_FILE_SIZE];
    int key;

    // Open the encrypted file
    fileIn = fopen("demo1.txt", "r");
    if(fileIn == NULL){
        printf("File open error.\n");
        return 0;
    }

    // Read the encrypted message from given file
    fgets(message, MAX_FILE_SIZE, fileIn);

    // Close the input file
    fclose(fileIn);

    // Prompt user to enter the key
    printf("Enter key: ");
    scanf("%d", &key);

    // Decrypt the message
    decrypt(message, key);

    // Open the output file
    fileOut = fopen("decrypted.txt", "w");
    if(fileOut == NULL){
        printf("File write error.\n");
        return 0;
    }

    // Write the decrypted message to output file
    fprintf(fileOut, "%s", message);

    // Close the output file
    fclose(fileOut);

    printf("File decrypted successfully.\n");

    return 0;
}