在C ++中加密/解密ROT

时间:2017-05-06 14:02:05

标签: c++ encryption caesar-cipher

HZROT.cpp:

#include "HZROT.h"

std::string ROTEncode(std::string instring, int rot)
{
    std::string result;
    for (char a : instring)
    {
        if (a >= 'A' && a <= 'Z')
            result += ((int)a + rot) % (int)'Z';
        else if (a >= 'a' && a <= 'z')
            result += ((int)a + rot) % (int)'z';
        else
            result += a;
    }
    return result;
}
std::string ROTDecode(std::string instring, int rot)
{
    std::string result;
    for (char a : instring)
    {
        if (a >= 'A' && a <= 'Z')
                result += ((int)a - rot + (int)'Z') % (int)'Z';
        else if (a >= 'a' && a <= 'z')
            result += ((int)a - rot + (int)'z') % (int)'z';
        else
            result += a;
    }
    return result;
}

HZROT.h:

#include <string>
std::string ROTEncode(std::string instring, int rot);
std::string ROTDecode(std::string instring, int rot);

我使用此代码加密/解密ROT,但它无法正常工作: 命令行:

C:\Users\adm1n\Desktop\C\HZToolkit>hztoolkit --erot 13 abcdefghijklmnopqrstuvwyz

输出:nopqrstuvwxy 因此它在'l'之后不适用于字母。你能救我吗?

1 个答案:

答案 0 :(得分:0)

工作代码是:

#include "HZROT.h"

std::string ROTEncode(std::string instring, int rot)
{
    std::string result;
    for (char a : instring)
    {
        if (IsBigLetter(a))
            result += ((int)a - (int)'A' + rot) % 26 + 'A';
        else if (IsSmallLetter(a))
            result += ((int)a - (int)'a' + rot) % 26 + 'a';
        else
            result += a;
    }
    return result;
}
std::string ROTDecode(std::string instring, int rot)
{
    std::string result;
    for (char a : instring)
    {
        if (IsBigLetter(a))
            result += ((int)a - (int)'A' - rot + 26) % 26 + 'A';
        else if (IsSmallLetter(a))
            result += ((int)a - (int)'a' - rot + 26) % 26 + 'a';
        else
            result += a;
    }
    return result;
}

和HZROT.h:

#include <string>

#define IsBigLetter(a) a >= 'A' && a <= 'Z'
#define IsSmallLetter(a) a >= 'a' && a <= 'z'

std::string ROTEncode(std::string instring, int rot);
std::string ROTDecode(std::string instring, int rot);