Implement a cryptographic system using the Caesar cipher method. - C Data Structure

C examples for Data Structure:Encrypt Decrypt

Description

Implement a cryptographic system using the Caesar cipher method.

Demo Code

#include <stdio.h>
#include <string.h>

#define  KEY  5/*from  w w w  .j  a v a2s  .co  m*/

char *msgOriginal = "this is a test";
char msgEncrypt[100];
char msgDecrypt[100];
int intChoice, length;

void encryptMsg()
{
  int i, ch;
  fflush(stdin);
  length = strlen(msgOriginal);
    for(i = 0; i < length; i++) {
      ch = msgOriginal[i];
      if(ch >= 'a' && ch <= 'z') {
        ch = ch + KEY;
        if(ch > 'z')
          ch = ch - 'z' + 'a' - 1;
         msgEncrypt[i] = ch;
      }
      else if(ch >= 'A' && ch <= 'Z'){
        ch = ch + KEY;
        if(ch > 'Z')
          ch = ch - 'Z' + 'A' - 1;
        msgEncrypt[i] = ch;
      }
    }
  msgEncrypt[length] = '\0';
  printf("\nEncrypted Message: %s", msgEncrypt);
}

void decryptMsg()
{
  int i, ch;
  fflush(stdin);
  printf("Enter the Message to Decrypt (upto 100 alphabets):\n");
  gets_s(msgEncrypt);
  length = strlen(msgEncrypt);
  for(i = 0; i < length; i++) {
    ch = msgEncrypt[i];
    if(ch >= 'a' && ch <= 'z') {
      ch = ch - KEY;
      if(ch < 'a')
        ch = ch + 'z' - 'a' + 1;
      msgDecrypt[i] = ch;
    }
    else if(ch >= 'A' && ch <= 'Z'){
      ch = ch - KEY;
      if(ch < 'A')
        ch = ch + 'Z' - 'A' + 1;
      msgDecrypt[i] = ch;
    }
  }
  msgDecrypt[length] = '\0';
  printf("\nDecrypted Message: %s", msgDecrypt);
}

void main()
{
    encryptMsg();
    decryptMsg();
}

Result


Related Tutorials