Implement a cryptographic system using the One-Time Pad cipher method. - C Data Structure

C examples for Data Structure:Encrypt Decrypt

Description

Implement a cryptographic system using the One-Time Pad cipher method.

Demo Code

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

char *msgOriginal = "this is a test";
char msgEncrypt[100];
char msgDecrypt[100];
char msgKey[100];
int intChoice, lenKey, lenMsg, intKey[100];

void generateKey()
{
   int i, randNum, num, seed = 6;
   lenKey = lenMsg;/*from   www.j  av a 2  s  . c o m*/

   for (i = 0; i < lenKey; i++) {
      randNum = i;
      num = randNum % 26;
      msgKey[i] = num + 65;
      intKey[i] = num;
   }
   msgKey[lenKey] = '\0';
   printf("\nKey: %s", msgKey);
}

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

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

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

Related Tutorials