0

我制作了用于密钥 rot7 和 rot13 的小型加密程序。除了两个 6 个字母 uvwxyz 外,一切正常。

如果我输入 ABCDEFGHIJKLMNOPQRSTUVWXYZ 它加密和解密没有问题。但是,如果我用小写字母输入相同的内容,那么 uvwxyz 将不起作用。

话虽如此,我已经允许 ascii 表中的所有可写字符作为有效范围,如下所示:

// allow all writable characters from 32 to 255
if ((str[i] >= 32 ) && (str[i] <=255))
{
    str[i] -= key;
}

下面是加密过程:

    cout << endl;
    cout << "Encrypting process started " << endl << endl;
    cout << "--------------------------- " << endl;

    //get the string length
    int i = 0;
    int length = str.length();
    int key = rot13 ;
    int k = 5;
    int multiple = 0;
    int count = 0;

    cout << "the text to encrypt is: " << str << endl;
    cout << "text length is: " << length << endl; 
    cout << "using rot13"<<endl;
    cout <<"---------------------------" << endl;
    cout << "using rot13" << endl;

    //traverse the string
    for(i = 0; i < length; i++)
    {

        count ++;

       cout << left;

       //if it is a multiple of 5 not the first character change the key 
        if((multiple = (( i % 5 ) == 0)) && (count != 1)  && (key == rot13)){

            key = rot7;


        }
        //if it is a multiple of 5 not the first character change the key 
        else if((multiple = (( i % 5 ) == 0)) && (count != 1) && (key == rot7) ) {

            key = rot13;


        }


        // Capital letters are 65 to 90  (a - z)
        if ((str[i] >= 32) && (str[i] <= 255))
        {
            str[i] += key;
        }


    }
    return str;

如果我允许这个范围,大写字母怎么可能起作用而不是小写字母?会不会是因为别的原因?我已经将这些捕获添加到一步一步发生的事情中......希望这会有所帮助

4

1 回答 1

4

在您的代码中:

    if ((str[i] >= 32) && (str[i] <= 255))
        {
           if (str[i] + key > 255)
               str[i] = ((str[i] + key) % 255 )+ 32;
           else
               str[i] += key;
        }

如果key值为 13 并且str[i]为 'u' 或更大,str[i]则其值高于 255。

在这种情况下,您应该使用模%运算符,这是旋转,而不仅仅是移位

于 2013-04-09T15:47:13.723 回答