Reputation: 3389
I am trying to make a very simple Caesar cipher algorithm to encrypt and decrypt the player's data in my game , but i am getting some weird results.The task of the algorithm is simple, just push foward or backwards the characters in the ascii table.
std::string Encrypt(std::string in,int key)
{
const char* chars=in.data();
char* newchar=(char*)malloc(sizeof(char)*in.length());
for(int c=0;c<in.length();c++)
{
newchar[c]=char(((int)chars[c])+key);//I suspect somewhere here is the problem
}
std::string out(newchar);
return out;
}
LOGI("encrypt:%s",Encrypt("hello",10).data());
LOGI("decrypt:%s",Encrypt(Encrypt("hello",10),-10).data());
Output:
encrypt:rovvyu@
decrypt:hellok
I dont know much about encryption and i know less about how ascii and the whole character thing works in c
Upvotes: 1
Views: 7274
Reputation: 1137
If you want to just know how to make a Caesar cipher, cool. If you actually want to protect some data, don't do this! It is no more a cryptographic method than pig latin.
Instead, use a pre-written encryption library. Don't write your own because it takes a long time to get it right. AES is fast and good enough for most cases, and has libraries for just about every programming language.
Upvotes: -1
Reputation: 7698
The problem is that adding "key" to a value in a..z may not land back in that range. Something like
if (chars[c] >= 'a' && chars[c] <='z') newchar[c] = 'a' + ((chars[c]-'a'+key)%26);
else if (chars[c] >= 'A' && chars[c] <='Z') newchar[c] = 'A' + ((chars[c]-'A'+key)%26);
else newchar[c] = chars[c];
Hope you have a good reason for using something so weak. BTW, use 26-key to invert.
Upvotes: 0
Reputation: 9716
std::string Encrypt(const std::string & in, int key)
{
std::string out(in);
for(int i=0; i < in.length(); ++i)
{
out[i] += key;
}
return out;
}
Upvotes: 4