This blog is under construction

Tuesday 9 July 2013

C program to implement ceaser cipher

Write a C program to implement ceaser cipher.


  #include <stdio.h>
  #include <string.h>
  int main() {
        char pText[100], cipher[100], val;
        int i = 0, key;

        /* get the plain text from the user */
        printf("Enter the plain text(all caps):");
        fgets(pText, 100, stdin);

        /* key to convert plain text to cipher text */
        printf("Enter the key to create cipher text(1 - 5):");
        scanf("%d", &key);
        pText[strlen(pText) - 1] = '\0';

        /* converting plain text to cipher text */
        while (pText[i] != '\0') {
                if ((pText[i] + key) > 'Z') {
                        val = (pText[i] + key) - 'Z';
                        cipher[i] = 'A' + val - 1;
                } else {
                        cipher[i] = pText[i] + key;
                }
                i++;
        }

        cipher[i] = '\0';

        printf("Caesar Cipher Text: %s\n", cipher);
        i = 0;

        /* converting cipher text to plain text */
        printf("Plain Text:");
        while (cipher[i] != '\0') {
                if ((cipher[i] - key) < 'A') {
                        printf("%c", 'Z' + 1 - ('A' - (cipher[i] - key)));
                } else {
                        printf("%c", cipher[i] - key);
                }
                i++;
        }
        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the plain text(all caps):HELLOWORLD
  Enter the key to create cipher text(1 - 5):4
  Ceasar Cipher Text: LIPPSASVPH
  Plain Text:HELLOWORLD





See Also:

No comments:

Post a Comment