【发布时间】:2017-11-24 22:45:48
【问题描述】:
我正在尝试在 C 中实现 Vigenere 的密码,但问题是当我尝试重复它所在的数组中使用的密钥时,它会在第 4 个字母之后中断。因此,如果密钥是 ABC,明文是 HELLO,则返回 HFNLO 而不是 HFNLP。当我查看我的代码时,它在逻辑上是有道理的,但它似乎只是不起作用。有人能看出问题吗?
代码如下:
int main(int argc, string argv[])
{
if(argc != 2)
{
printf("usage: ./vigenere k\n");
return 1;
}
//asks for plain text
printf("plaintext: ");
string text = get_string();
string k = argv[1];
printf("ciphertext: ");
//checks to see if length of key is shorter than length of plaintext and duplicates it.
int count = 0;
while(strlen(k) <= strlen(text))
{
k[strlen(k + count)] = k[count];
count++;
}
//changes key to be within 0 - 25 and encrypts plaintext
for(int i = 0; i < strlen(text); i++)
{
if(k[i] >= 'A' && k[i] <= 'Z')
{
k[i] = k[i] - 65;
}
else if (k[i] >= 'a' && k[i] <= 'z')
{
k[i] = k[i] - 97;
}
//if statement for plaintext capital letters
if(text[i] >= 'A' && text[i] <= 'Z')
{
text[i] = text[i] - 64;
text[i] = ((text[i] + k[i]) % 26) + 64;
}
//if statement for plaintext lowercase letters
else if(text[i] >= 'a' && text[i] <= 'z')
{
text[i] = text[i] - 96;
text[i] = ((text[i] + k[i]) % 26) + 96;
}
//prints final cipher
printf("%c", text[i]);
}
printf("\n");
return 0;
}
【问题讨论】:
-
k是什么?和strlen(k + count)肯定看起来很可疑。 -
在键索引上使用模数运算符,而不是这个坏事。比如
k[i % strlen(k)](为了说明:做一些更有效率的事)。