0

我在尝试使我的代码正常工作时遇到了一些问题。它打印了几乎正确的数据,但可能没有正确循环?我认为它不会通过字母表重复键。都是小写,不超过26。

void vigenereEncrypt( const char  plaintext[], char ciphertext[], const char key[] )

{
int idx;
int j;

for( idx = 0, j = 0; idx <= strlen(plaintext); idx++ )
{
    if ( CHAR_OUT_OF_RANGE(plaintext[idx]) )
    {
        ciphertext[idx] = plaintext[idx];
    }
    else
    {
        ciphertext[idx] = plaintext[idx];
        ciphertext[idx] += key[j] - MIN_ASCII_VALUE;

        if (ciphertext[idx] >= MAX_ASCII_VALUE) ciphertext[idx] += -MAX_ASCII_VALUE + MIN_ASCII_VALUE - 1;
    }
    j = (j + 1) % strlen(key);
}

ciphertext[idx] = 0;    
}

例如:如果我使用 jerry 键输入明文墨粉,则输出将为 csevé。它应该将其更改为 csvp

4

2 回答 2

0

帮每个人(尤其是你自己)一个忙,并使用std::string而不是 C 风格的字符串。然后使用标准算法而不是自己编写搞乱循环。

#include <iostream>
#include <iterator>
#include <algorithm>

class crypt {
    std::string key;
    size_t pos;
public:
    crypt(std::string const &k) : key(k), pos(0) { }

    char operator()(char input) { 
        char ret = input ^ key[pos]; 
        pos = (pos + 1) % key.size(); 
        return ret; 
    }
};

int main() {
    std::string input("This is some input to be encrypted by the crappy encryption algorithm.");

    std::transform(input.begin(), input.end(),
        std::ostream_iterator<char>(std::cout),
        crypt("This is the key"));
    return 0;
}
于 2014-02-04T07:01:31.180 回答
0

Your loop is going one-to-far. You should use < instead of <=. And I assume you should be testing for > MAX_ASCII_VALUE, not >= (but you haven't shown what MAX_ASCII_VALUE is).

But your basic problem is a signed vs. unsigned char problem. With signed chars, when it goes above 127 it wraps around and becomes negative, so the > test will fail when it should have passed.

void vigenereEncrypt(const char plaintext[], char ciphertext[], const char key[])
{
    size_t i, j;
    for(i = 0, j = 0; i < strlen(plaintext); ++i )
    {
        ciphertext[i] = plaintext[i];
        if (!CHAR_OUT_OF_RANGE(plaintext[i]))
        {
            ciphertext[i] += (uchar)key[j] - (uchar)MIN_ASCII_VALUE;

            if ((uchar)ciphertext[i] > (uchar)MAX_ASCII_VALUE)
                ciphertext[i] -= (uchar)MAX_ASCII_VALUE - (uchar)MIN_ASCII_VALUE + 1;
        }
        j = (j + 1) % strlen(key);
    }

    ciphertext[i] = 0;
}
于 2014-02-04T06:45:15.247 回答