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

C examples for Data Structure:Encrypt Decrypt

Description

Implement a cryptographic system using the Transposition cipher method.

Demo Code

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

#define  KEY  7/*from  w w  w.j a v  a2s  .  c  o  m*/

char *msgToEncrypt = "this is a test";
char msgToDecrypt[110];
char msgEncrypt[20][KEY];
char msgDecrypt[20][KEY];
int intChoice, length;

void encryptMsg()
{
  int row, col, rows, cilr, length, k = 0;
  length = strlen(msgToEncrypt);
  rows = (length/KEY) + 1 ;
  cilr = length % KEY; /* cilr - characters in last row */
  for(row = 0; row < rows; row++) {
   for(col = 0; col < KEY; col++) {
     msgEncrypt[row][col] = msgToEncrypt[k++];
     if (k == length) break;
   }
  }
 printf("\nEncrypted Message: \n");
  for(col = 0; col < KEY; col++) {
   for(row = 0; row < rows; row++) {
     if ((col >= cilr) && (row == (rows-1)))
       continue;
     printf("%c", msgEncrypt[row][col]);
   }
  }
}

void decryptMsg()
{
  int row, col, rows, cilr, length, k = 0;
  printf("Enter the Message (20 to 110 letters) to be Decrypted: \n");
  fflush(stdin);
  gets_s(msgToDecrypt);
  length = strlen(msgToDecrypt);
  rows = (length/KEY) + 1 ;
  cilr = length % KEY;    /* cilr - characters in last row */
  for(col = 0; col < KEY; col++) {
   for(row = 0; row < rows; row++) {
     if ((col >= cilr) && (row == (rows-1)))
       continue;
     msgDecrypt[row][col] = msgToDecrypt[k++];
     if (k == length) break;
   }
  }
  printf("\nDecrypted Message: \n");
  for(row = 0; row < rows; row++) {
   for(col = 0; col < KEY; col++) {
     printf("%c", msgDecrypt[row][col]);
   }
  }
}

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

Result


Related Tutorials