Cipher-decipher Program in C

In the language of cryptography, ciphertext refers to a message encoded with a particular key. Plaintext refers to the original, unencoded text. In this problem, both the ciphertext and the key are simply strings of upper-case characters. The ciphertext is generated from the plaintext by “adding” corresponding characters of the plaintext and the key together. If the plaintext is shorter than the key, only some of the key will be used. Similarly, if the plaintext is shorter than the key, the key will be used multiple times.

For example, to encode the plaintext “HELLO” with the key “CAT”:
Plaintext: HELLO
Key: CATCA
Ciphertext: KFFOP

And to encode the plaintext “DOG” with the key “FIDO”:
Plaintext: DOG
Key: FID
Ciphertext: JXK

To add two letters together, use the following convention: A=1, B=2, …, Z=26. If the sum of two letters is greater than 26, subtract 26 from the sum. For example: A + E = 1 + 5 = 6 = F, and D + X = 4 + 24 = 28 = 2 = B.

Given a ciphertext/key pair, determine the corresponding plaintext.

Input Format :
Input will consist of pairs of lines, with the first line being the ciphertext and the second line being the key. Both will consist of only uppercase letters.
Output Format:
For each ciphertext/key pair, print the corresponding plaintext message.

Example:
Sample Input:
HELLO
CAT

Sample Output:
KFFOP

Code:

#include<stdio.h>
#include<string.h>
int main()
{
  char p[50]={0},key[50]={0};
  int x=0;
  char c[50]={0};
  int i,l1,l2;
  gets(p);
  gets(key);
  l1=strlen(p);
  l2=strlen(key);
  if(l1<=l2)
  {
    goto END;
  }
  else if(l1>l2)
  {
    for(i=l2;i<l1;i++)
    {
      key[i]=key[x];
      x++;
    }
  } 
  for(i=0;i<l1;i++)
  {
    p[i]=(int)p[i]-64;
    key[i]=(int)key[i]-64;
    c[i]=p[i]+key[i];
    if(c[i]>26)
      c[i]=c[i]-26;
    c[i]=c[i]+64;
    printf("%c",c[i]);
  }
  return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *