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

C examples for Data Structure:Encrypt Decrypt

Description

Implement a cryptographic system using the Simple Substitution cipher method.

Demo Code

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

char *msgOriginal = "this is a test";
char msgEncrypt[100];
char msgDecrypt[100];
int intEncryptKey[26], intDecryptKey[26];
int intChoice, i, j, seed, length, randNum, num, flag = 1, tag = 0;

void generateKey()
{
  printf("\nEnter seed S (1 <= S <= 30000): ");
  scanf("%d", &seed);
  srand(seed);//from   ww  w . j a v  a 2  s.  c o  m
  for(i=0; i < 26; i++)
    intEncryptKey[i] = -1;
  for(i=0; i < 26; i++) {
    do {
      randNum = rand();
      num = randNum % 26;
      flag = 1;
      for(j = 0; j < 26; j++)
        if (intEncryptKey[j] == num)
           flag = 0;
        if (flag == 1){
          intEncryptKey[i] = num;
          tag = tag + 1;
        }
    } while ((!flag) && (tag < 26 ));
  }
  printf("\nEncryption KEY = ");
  for(i=0; i < 26; i++)
    printf("%c", intEncryptKey[i] + 65);
  for(i = 0; i < 26; i++) {
    for(j = 0; j < 26; j++) {
      if(i  == intEncryptKey[j]) {
        intDecryptKey[i] = j ;
        break;
      }
    }
  }
  printf("\nDecryption KEY = ");
  for(i=0; i < 26; i++)
    printf("%c", intDecryptKey[i] + 65);
}

void encryptMsg()
{
  length = strlen(msgOriginal);
  for (i = 0; i < length; i++)
    msgEncrypt[i] = (intEncryptKey[(msgOriginal[i]) - 65]) + 65;
  msgEncrypt[length] = '\0';
  printf("\nEncrypted Message: %s", msgEncrypt);
}

void decryptMsg()
{
  printf("Enter the Message to Decrypt (upto 100 chars): \n");
  fflush(stdin);
  gets_s(msgEncrypt);
  length = strlen(msgEncrypt);
  for (i = 0; i < length; i++)
   msgDecrypt[i] = (intDecryptKey[(msgEncrypt[i]) - 65]) + 65;
   msgDecrypt[length] = '\0';
   printf("\nDecrypted Message: %s", msgDecrypt);
}

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

Result


Related Tutorials