The Caesar cipher, named after Julius Caesar, is one of the most well-known tech
ID: 3811001 • Letter: T
Question
The Caesar cipher, named after Julius Caesar, is one of the most well-known techniques used to encrypt messages. Caesar's cipher was used to protect military messages by shifting each letter in the message by 3 characters in the alphabet. When the message was delivered, the recipient would shift each letter by 3 places the opposite direction and the actual message would appear. Unfortunately, as you probably know, the Caesar cipher is very weak and can be easily broken by letter frequency analysis. For this in-class, you are to: Ask the user for a lowercase string containing no spaces Read in the string Ask the user for an integer shift factor to the right Read in the shift Write a function to encrypt the string Print out the new string Decrypt the string too. You should be able to test your function by encrypting and decrypting a string with the same shift value to obtain the original, unencrypted string. Check to be sure the user only enters lower-case letters and no spaces and enforce this with a do-while loop.Explanation / Answer
#include <iostream>
#include<algorithm>
#include <cstring>
using namespace std;
class cypher
{
public:
void encrypt(string str,int sf)
{
int i,len,ac;
string str1;
char c,c1;
//len=strlen(str);
for(unsigned int i = 0; i<str.length(); i++)
{
c = str[i]; //this is your character
ac=(int)c;
ac=ac+sf;
c1=(char)ac;
str1=str1+c1;
}
std::cout<<"The encrypted string ";
std::cout<<str1<<" ";
}
void decrypt(string str,int sf)
{
int i,len,ac;
string str1;
char c,c1;
//len=strlen(str);
for(unsigned int i = 0; i<str.length(); i++)
{
c = str[i]; //this is your character
ac=(int)c;
ac=ac-sf;
c1=(char)ac;
str1=str1+c1;
}
std::cout<<"The decrypted string ";
std::cout<<str1<<" ";
}
};
int main()
{
cypher obj;
string org;
int ch,val,val1;
cout<<"Enter a sting in lower case with no space ";
cin>>org;
transform(org.begin(), org.end(), org.begin(),::tolower);
remove_if(org.begin(), org.end(), isspace);
cout<<"1.Encrypt String ";
cout<<"2.Decrypt String ";
cout<<"Enter your choice ";
cin>>ch;
switch (ch)
{
case 1:
cout<<"Enter the right shift factor ";
cin>>val;
obj.encrypt(org,val);
break;
case 2:
cout<<"Enter the left shift factor ";
cin>>val1;
obj.decrypt(org,val1);
break;
default:
cout<<"Invalid ";
break;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.