Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;简单凯撒密码算法_C++_Encryption_Char - Fatal编程技术网

C++ c++;简单凯撒密码算法

C++ c++;简单凯撒密码算法,c++,encryption,char,C++,Encryption,Char,我试图制作一个非常简单的Caesar密码算法来加密和解密游戏中玩家的数据,但我得到了一些奇怪的结果。该算法的任务很简单,只需向前或向后推ascii表中的字符 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();

我试图制作一个非常简单的Caesar密码算法来加密和解密游戏中玩家的数据,但我得到了一些奇怪的结果。该算法的任务很简单,只需向前或向后推ascii表中的字符

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());
我对加密知之甚少,对ascii和整个字符在c中的工作原理知之甚少。

std::string Encrypt(const std::string&in,int key)
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;
}
{ std::串出(in); 对于(int i=0;i
问题在于,向a..z中的值添加“键”可能无法返回该范围。差不多

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

if(chars[c]>='a'&&chars[c]='a'&&chars[c]如果你只想知道如何制作凯撒密码,酷。如果你真的想保护一些数据,不要这样做!这不仅仅是一种加密方法,更像是一种拉丁语


相反,请使用预先编写的加密库。不要编写自己的加密库,因为这需要很长时间才能正确完成。AES在大多数情况下都足够快和好,几乎每种编程语言都有库。

正在解密游戏的文本部分,如果没有,为什么不使用现有库中的现代加密技术s字母替换算法在当今时代对任何保护都没有用处。见鬼,人们这样做只是为了好玩。
sizeof(char)==1
,根据定义。你应该释放
newchar
out
将制作自己的字符串副本。如果你已经在使用
std::string
为什么要malloc输出数组?@Scott,我不想使用任何外部库,因为我想保持它的简单,我也不在乎用户找到真正的数据,我只是想不要让它对他们造成不便。
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];