#include <iostream>
using namespace std;
class Caesar
{
int key;
string plain;
string cipher;
public:
void setKey(int key)
{
this->key = key;
}
void setPlain(string plain)
{
this->plain = plain;
}
void setCipher(string cipher)
{
this->cipher = cipher;
}
void encrypt()
{
for(int i=0;i<plain.length();i++)
{
if(isalpha(plain[i]))
{
if(islower(plain[i]))
cipher += (plain[i]+key-'a')%26+'a';
else
cipher += (plain[i]+key-'A')%26+'A';
}
else
cipher += plain[i];
}
}
void decrypt()
{
for(int i=0;i<cipher.length();i++)
{
if(isalpha(cipher[i]))
{
if(islower(cipher[i]))
plain += (cipher[i]-key-'a'+26)%26+'a';
else
plain += (cipher[i]-key-'A'+26)%26+'A';
}
else
plain += cipher[i];
}
}
string getPlainText()
{
return plain;
}
string getCipherText()
{
return cipher;
}
};
int main()
{
Caesar caesar;
int choice;
string plain,cipher;
int key;
cout<<"Press 1 for encryption, 2 for decryption-";
cin>>choice;
if(choice == 1)
{
/* encryption */
cout<<"Enter key-";
cin>>key;
cout<<"Enter plain text-";
cin>>plain;
caesar.setKey(key);
caesar.setPlain(plain);
caesar.encrypt();
cout<<"Cipher text = "<<caesar.getCipherText()<<endl;
}
else if(choice == 2)
{
/* decryption */
cout<<"Enter key-";
cin>>key;
cout<<"Enter cipher text-";
cin>>cipher;
caesar.setKey(key);
caesar.setCipher(cipher);
caesar.decrypt();
cout<<"Plain text = "<<caesar.getPlainText()<<endl;
}
return 0;
}

Blogger Comments:
Emoticon Emoticon