1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
|
#include <iostream>
#include <string>
#include <stdio.h>
#include <ctype.h>
#include <fstream>
#include <sstream>
#include <cstdlib>
using namespace std;
void alpha_to_num(char &ch){
ch -= 'A';
}
void num_to_alpha(int &num){
num += 'A';
}
void encoding (int &c,int p,int k){
c = (p+k)%26;
}
void decoding ( int &c, int p, int k){
if((c-k )<0)
{
p = ((c+26)-k)%26;
}
else
{
p = (c-k)%26;
}
}
int main(){
string keyword;
string plaintext;
int c = 0;
int k;
int p;
int c2;
char action;
k= (int)keyword.length();
p = (int)plaintext.length();
string line;
ifstream myfile ("value.txt");
if (myfile.is_open())
{
while ( getline (myfile,keyword) )
myfile.close();
}
else cout << "Unable to open file.Please rename the key word file as 'value.txt'\n";
cout<< "Enter the message:\n";
getline(cin,plaintext);
cout<<"Enter E to encrypt or D to decrypt:\n";
cin>>action;
string zKeyword;
for (int count=0; count < plaintext.length(); count++)
{
if (keyword.length() != plaintext.length())
{
if (keyword.length()<=plaintext.length())
{
keyword = keyword+keyword[count];
}
}
}
if(action == 'E')
{
for (int i=0;i<(int)keyword.length();i++)
{
keyword[i] = toupper(keyword[i]);
alpha_to_num(keyword[i]);
}
for(int j=0;j<(int)plaintext.length(); j++)
{
plaintext[j] = toupper(plaintext[j]);
alpha_to_num(plaintext[j]);
}
for(int k=0;k<(int)plaintext.length(); k++)
{
encoding (c,plaintext[k],keyword[k]);
num_to_alpha(c);
cout<< (char)c<<endl;
ofstream myfile;
myfile.open ("example.txt" , ios::out | ios::app );
myfile << (char)c;
myfile.close();
}
}
else if(action == 'D')
{
for (int i=0;i<(int)keyword.length();i++)
{
keyword[i] = toupper(keyword[i]);
alpha_to_num(keyword[i]);
}
for(int j=0; j<(int)plaintext.length(); j++)
{
plaintext[j] = toupper(plaintext[j]);
alpha_to_num(plaintext[j]);
}
for(int m=0;m<(int)plaintext.length(); m++)
{
decoding (c,plaintext[m],keyword[m]);
num_to_alpha(c);
cout<< (char)c<<endl;
ofstream myfile;
myfile.open ("example.txt" , ios::out | ios::app );
myfile << (char)c;
myfile.close();
}
}
else
cout << "INVALID ENTRY! Please enter 'e' to encrypt or 'd to decrypt" << endl;
if( remove( "value.txt" ) != 0 )
perror( "Error deleting file" );
else
puts( "File successfully deleted" );
return 0;
}
|