I just did a small text encryption example. But I am unsure how I can make it better. eg. If I read in a text file how to have more "random" series of encryption but still being to reverse the effects to decrypt.
My main problem is I'm terrible with math, so can't really think of a better way to do this. Thanks for looking.
#include <iostream>
#include <string>
char * cstr;
std::string encrypt(std::string);
std::string decrypt(std::string);
int main()
{
std::string input, temp;
std::cout << "Enter string to be encrypted:";
getline(std::cin,input);
// now encrpyt and print results
temp = encrypt(input);
std::cout << "Encrypted text:" << std::endl;
std::cout << temp << std::endl;
// now decrypt same
temp = decrypt(temp);
std::cout << "Decrypted text:" << std::endl;
std::cout << temp << std::endl;
return 0;
}
std::string encrypt(std::string str)
{
cstr = newchar[str.size()+1];
strcpy(cstr,str.c_str());
for (int i=0; i<str.size(); i+=2)
{
if (cstr[i]!=' ')
cstr[i]=++cstr[i];
}
int temp = str.size();
str = "";
for (int j=0;j<temp;j++)
str += cstr[j];
return str;
}
std::string decrypt(std::string str)
{
cstr = newchar[str.size()+1];
strcpy(cstr,str.c_str());
for (int i=0;i<str.size();i+=2)
{
if (cstr[i]!=' ')
cstr[i]=--cstr[i];
}
int temp=str.size();
str = "";
for (int j=0;j<temp;j++)
str += cstr[j];
return str;
}
at the moment it is simply incrementing every 2nd letter that is not a space. was not until after I added the conditional that I realized I could probably increment the space also.
I'm guessing a math based recursion implementation would probably be better, but I have no idea what formula I could use.
EDIT: Also I had problems using strcpy to copy the string back which is why I had to add the :
int temp=str.size();
str = "";
for (int j=0;j<temp;j++)
str += cstr[j];
i cant compile the notepad program but maybe you can. i think one thread discusses it here and says it works for old compilers. i dont know, but the ecryption program it good.
"This is a program I wrote using vigenere algorithm."
is all it states.
Also I had problems using strcpy to copy the string back which is why I had to add the :
int temp=str.size();
str = "";
for (int j=0;j<temp;j++)
str += cstr[j];
was just a slack work around...
error message was cannot convert const char * to char *
I don't understand that error. well I do, but I don't understand why it thinks str.c_str() is const.
here is a simple encode/decoder that you might want to incorporate, you choose the 'key' and it will encrypt and decrypt according to the key you select.
I don't see why there is any need to go from a string to a C-style string and back in the original post. Why not just operate on the characters of the string in place?
1 2 3 4 5 6 7
string s = "asdf";
for( string::iterator i = s.begin(); i != s.end(); ++i )
{
// do whatever encryption/decryption you like
*i = *i ^ 25;
}