In: Computer Science
Write a program in c++ that can perform encryption/decryption. In the following let the alphabet A be A={A, a, B, b, . . ., “ ”, “.”,“’ ”}. The encoding is A→0, a→1, B→2, b→4, . . ., Z→50, z→51, “ ”→52, “.”→53 and “’”→54.
For this code, we take a string text and ask the user to enter the plain text to encrypt. Then we take separate conditions for capital, small, and special characters and reduce them to the corresponding numbers and generate the cipher.
For decryption we ask the user for length of the code and the code itself. then we just use the separate conditions and reverse the formulas to get the plain text out of the code.
CODE:
/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile
and execute it.
*******************************************************************************/
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string text;
int code[100];
int cypher[100];
cout<<"Enter plain text to be encrypted: ";
getline(cin, text);
cout<<"Encrypted text: ";
for (int i=0; i<text.length(); i++)
{
if(text[i]>=65 && text[i]<=90)
{
cypher[i] = (text[i]%65)*2;
}
else if(text[i]>=97 && text[i]<=122)
{
cypher[i] = ((text[i]%97)*2)+1;
}
if(text[i] == 32)
{
cypher[i] = 52;
}
if(text[i] == 46)
{
cypher[i] = 53;
}
if(text[i] == 39)
{
cypher[i] = 54;
}
cout<<cypher[i]<<" ";
}
int len;
cout<<"\nEnter the length of the cypher to decrypt: ";
cin>>len;
cout<<"Now enter the cypher: ";
for(int i=0; i<len; i++)
cin>>code[i];
cout<<"Decrypted text is: ";
for(int i=0; i<len; i++)
{
if(code[i]%2 == 0 && code[i] < 52)
text[i] = (code[i]/2) + 65;
if(code[i]%2 !=0 && code[i] <52)
text[i] = ((code[i]-1)/2) + 97;
if(code[i]==52)
text[i] = 32;
if(code[i]==53)
text[i] = 46;
if(code[i]==54)
text[i] = 39;
cout<<text[i];
}
return 0;
}
OUTPUT: