Random mono-alphabet cipher. The Caesar cipher, which shifts all letters by a fi
ID: 3624962 • Letter: R
Question
Random mono-alphabet cipher. The Caesar cipher, which shifts all letters by a fixed amount, is far too easy to crack. Here is a better idea. As the key, don't use numbers but words. Suppose the key word is FEATHER. Then first remove duplicate letters, yielding FEATHR, and append the other letters of the alphabet in reverse order:
Now encrypt the letters as follows:
Write a program that encrypts or decrypts a file using this cipher. For example,
decrypts a file using the keyword FEATHER. It is an error not to supply a keyword.
*Use introduction level programming to solve this problem.
Explanation / Answer
please rate - thanks
#include <iostream>
#include <fstream>
#include<iomanip>
using namespace std;
void encrypt(string,istream&,ostream&);
void decrypt(string,istream&,ostream&);
string adjust(string);
int main(int argc, char * argv[])
{ifstream in;
ofstream out;
string key;
in.open(argv[3]);
if(in.fail()) //is it ok?
{ cout<<"file did not open please check it ";
system("pause");
return 1;
}
out.open(argv[4]);
key=argv[2];
if(key[0]!='-'&&key[1]!='k')
{cout<<"missing key program aborted ";
return 1;
}
key=adjust(key);
cout<<key<<endl;
if(strcmp(argv[1],"-d")==0)
decrypt(key,in,out);
else
encrypt(key,in,out);
in.close();
out.close();
return 0;
}
string adjust(string key)
{int count[26]={0};
char c;
int i;
bool found;
string newkey="";
for(i=2;key[i]!='';i++)
{key[i]=toupper(key[i]);
count[key[i]-'A']++;
}
for(i=0;i<26;i++)
cout<<(char)('A'+i)<<" "<<count[i]<<endl;
for(i=2;key[i]!='';i++)
if(count[key[i]-'A']!=0)
{newkey=newkey+key[i];
count[key[i]-'A']=0;
}
int len=newkey.length();
for(c='Z';c>='A';c--)
{found=false;
cout<<newkey<<" "<<newkey.length()<<endl;
for(i=0;i<len;i++)
if(c==key[i])
{found=true;
cout<<c<<" "<<i<<endl;
}
cout<<c<<" "<<found<<endl;
if(!found)
newkey=newkey+c;
}
cout<<newkey<<endl;
return newkey;
}
void encrypt(string w,istream& in,ostream& out)
{string buffer;
int i;
getline(in,buffer);
while(in)
{
for(i=0;buffer[i]!='';i++)
if(isalpha(buffer[i]))
{out<<w[toupper(buffer[i])-'A'];
cout<<toupper(buffer[i])-'A'<<" "<<w[toupper(buffer[i])-'A']<<" "<<i<<" "<<buffer[i]<<endl;
}
else
out<<buffer[i];
out<<endl;
getline(in,buffer);
}
}
void decrypt(string w,istream& in,ostream& out)
{string buffer;
int i,j;
getline(in,buffer);
while(in)
{
for(i=0;buffer[i]!='';i++)
if(isalpha(buffer[i]))
{for(j=0;j<w.length();j++)
if(toupper(buffer[i])==w[j])
out<<(char)('A'+j);
}
else
out<<buffer[i];
out<<endl;
getline(in,buffer);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.