For the life of me, I cannot figure out why I can encrypt text, but not decrypt it.
Here's the code, and I'll show you some sample output.
Code:
#include <iostream>
#include <fstream>
#include <string>
std::string encrypt(char fname[255]);
std::string decrypt(char fname[255]);
int main(int argc, char *argv[])
{
if (argc < 2)
{
std::cout << "\nThe correct usage is main.exe -[(e)ncrypt/(d)ecrypt/(h)elp].";
std::cin.get();
return(0);
}
if ((strcmp(argv[1], "-help") == 0) || (strcmp(argv[1], "-h") == 0) || (strcmp(argv[1], "-?") == 0))
{
std::cout << "\nAvailable options are -help (-h, -?), -encrypt (-e), and -decrypt (-d).";
std::cin.get();
return(0);
}
else if ((strcmp(argv[1], "-encrypt") == 0) || (strcmp(argv[1], "-e") == 0))
{
encrypt("crypt.dat");
}
else if ((strcmp(argv[1], "-decrypt") == 0) || (strcmp(argv[1], "-d") == 0))
{
decrypt("crypt.dat");
}
std::cin.get();
return(0);
}
std::string encrypt(char filename[255])
{
char buffer[65535];
const char key[9] = "CProgcom";
std::ofstream oFile(filename, std::ios::binary | std::ios::trunc);
std::cout << "\nInput text to be encrypted: ";
std::cin.getline(buffer, 65535, '\n');
int y = 0;
for (int x = 0; x < 65535; x++)
{
if (buffer[x] == '\0')
{
break;
}
std::cout << buffer[x] << " . " << key[y] << " . ";
buffer[x] = buffer[x]^(int)key[y];
y++;
std::cout << buffer[x] << "\n";
if (y >= 8)
{
y = 0;
}
}
oFile << buffer;
oFile.close();
return(0);
}
std::string decrypt(char fname[255])
{
char buffer[65535];
const char key[9] = "CProgcom";
std::ifstream iFile(fname, std::ios::binary);
iFile.getline(buffer, 65535, '\n');
int y = 0;
for (int x = 0; x < 65535; x++)
{
if (buffer[x] == '\0')
{
break;
}
std::cout << buffer[x] << " . " << key[y] << " . ";
buffer[x] = buffer[x]^(int)key[y];
y++;
std::cout << buffer[x] << "\n";
if (y >= 8)
{
y = 0;
}
}
std::cout << "\n" << buffer << "\n";
iFile.close();
return(0);
}
Output from Encryption:
Code:
T . C . ↨
h . P . 8
i . r . ←
s . o . ∟
. g . G
i . c .
s . o . ∟
. m . M
a . C . "
. P . p
t . r . ♠
e . o .
s . g . ¶
t . c . ↨
. . o . A
Output from Decryption:
Code:
↨ . C . T
8 . P . h
← . r . i
∟ . o . s
G . g .
Please help?