简体   繁体   中英

c++ simple Caesar cipher algorithm

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

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;
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM