In: Computer Science
Write a program that encrypts and decrypts the user input. Note – Your input should be only lowercase characters with no spaces. Your program should have a secret distance given by the user that will be used for encryption/decryption. Each character of the user’s input should be offset by the distance value given by the user
For Encryption Process:
Take the string and reverse the string.
Encrypt the reverse string with each character replaced with distance value (x) given by the user.
For Decryption:
Take the string and reverse the string.
Decrypt the reverse string with each character replaced with distance value (x) given by the user.
Sample
String input - udc
Encryption process – udc -> xgf (encrypted)
The program should ask the user for input to encrypt, and then display the resulting encrypted output. Next your program should ask the user for input to decrypt, and then display the resulting decrypted output.
Example
Enter phrase to Encrypt (lowercase, no spaces): udc
Enter distance value: 3
Result: xgf
Enter pharse to Decrypt: (lowercase, no spaces): xgf
Enter distance value: 3
Result: udc
Code(C++):-
#include <iostream>
using namespace std;
string reverse(string s)
{
int n=s.length();
for(int i=0;i<n/2;i++)
{
char c=s[i];
s[i]=s[n-i-1];
s[n-i-1]=c;
}
return s;
}
string Encrypt(string s,int d)
{
s=reverse(s); //Reverse String.
int n=s.length();
for(int i=0;i<n;i++)
{
s[i]=s[i]-97;
s[i]=(s[i]+d)%26;
s[i]=s[i]+97;
}
return reverse(s);
}
string Decrypt(string s,int d)
{
s=reverse(s); //Reverse String.
int n=s.length();
for(int i=0;i<n;i++)
{
s[i]=s[i]-97; //As Lower Case
letters start from Ascii 97
s[i]=(s[i]-d)%26;
s[i]=s[i]+97;
}
return reverse(s);
}
int main()
{
string s;
cout<<"Enter phrase to Encrypt (lowercase, no
spaces):";
cin>>s;
int d;
cout<<"Enter Distance:";
cin>>d;
d=d%26; //One Complete
Cycle of 26 characters in lower alphabet.
string s1=Encrypt(s,d); //Function for
Encryption.
cout<<"Result:"<<s1<<endl;
cout<<"Enter phrase to Decrypt (lowercase, no
spaces):";
cin>>s;
cout<<"Enter Distance:";
cin>>d;
d=d%26; //One Complete
Cycle of 26 characters in lower alphabet.
s1=Decrypt(s,d); //Function for Decryption.
cout<<"Result:"<<s1<<endl;
}