Encryption and Decryption using Polyalphabetic Ciphers by using C++ programming
ID: 3904342 • Letter: E
Question
Encryption and Decryption using Polyalphabetic Ciphers by using C++ programming language:
• Input
– A given text file for plaintext or ciphertext (assume only 26 letters, no special characters, numbers and punctuations)
– 3 substitution ciphers, M1,M2,M3
• M1 – left shift 3 letters
• M2 – Plain: a b c d e f g h i j k l m n o p q r s t u v w x y z
Cipher: D K V Q F I B J W P E S C X H T M Y A U O L R G Z N
• M3 – right shift 5 letters
– cycling pattern
• n=3: M1,M3,M2,M3; M1,M3,M2,M3;
• Output
– Encrypted ciphertext or decrypted plaintext
Explanation / Answer
#include<iostream>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
#include<fstream>
using namespace std;
int main(){
int k;
string msg;
string line;
string str1 = "abcdefghijklmnopqrstuvwxuz";
string str2 = "DKVQFIBJWPESCXHTMYAUOLRGZN";
ifstream fin("input.txt");
if (!fin){
cout << "Error opening file ";
return 0;
}
while (getline(fin,line)){
//cout << "Enter a message:" << endl;
//getline(fin,line);
msg = line;
cout << "1-Encrypt 2-Decrypt:" << endl;
int en;
getline(cin,line);
en = atoi(line.c_str());
cout << "1.M1 (left shift 3 letters)" << endl;
cout << "2.M2 (abcdefghijklmnopqrstuvwxyz)" << endl;
cout << " (DKVQFIBJWPESCXHTMYAUOLRGZN)" << endl;
cout << "3.M3 (left shift 3 letters)" << endl;
cout << "4.Exit" << endl;
cout << "Enter choice:";
int n;
//cin.ignore();
getline(cin,line);
n = atoi(line.c_str());
if (n == 4)
break;
if (n == 1){
//cout << "------------------------- ";
string ans = "";
//cout << msg << endl;
for (int i = 0; i<msg.length(); i++){
for (int j = 0; j<str1.length(); j++){
if (!isalpha(msg[i])){
ans = ans + msg[i];
break;
}
if (str1[j] == msg[i]){
if (en == 1){
k = (j - 3) % 26;
if (k < 0)
k = k + 26;
ans = ans + str1[k];
}
else if (en == 2){
k = (j + 3) % 26;
ans = ans + str1[k];
}
}
}
}
cout << ans << endl;
}
if (n == 2){
string ans = "";
for (int i =0; i<msg.length(); i++){
for (int j = 0; j<str1.length(); j++){
if (!isalpha(msg[i])){
ans = ans + msg[i];
break;
}
if (en == 1){
if (tolower(str1[j]) == msg[i]){
ans = ans + str2[j];
}
}
if (en == 2){
if (tolower(str2[j]) == msg[i]){
ans = ans + str2[j];
}
}
}
}
cout << ans << endl;
}
if (n == 3){
string ans = "";
for (int i =0; i<msg.length(); i++){
for (int j = 0; j<str1.length(); j++){
if (!isalpha(msg[i]))
ans = ans + msg[i];
if (en == 1){
if (str1[j] == msg[i]){
k = (j + 5) % 26;
ans = ans + str1[j];
}
}
if (en == 2){
if (str1[j] == msg[i]){
k = (j - 5) % 26;
if (k < 0)
k = 26 + j;
ans = ans + str1[k];
}
}
}
}
cout << ans << endl;
}
}
fin.close()
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.