0

我一直在研究这个 Vigenere 密码大约 8 个小时。你能帮我么?我认为主要问题在于算法 - 我不知道如何利用密钥长度(我知道我需要以某种方式获取它的 mod)。

#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        printf("Bad!");
        return 1;
    }
    int keylen = strlen(argv[1]);
    char *key = argv[1];
    for (int i = 0; i < keylen; i++)
        {
            if(isupper(key[i]))
            {
                key[i] = key[i]-65;
            }
            else if(islower(key[i]))
            {
                key[i] = key[i]-97;
            }
        }
    printf("Plaintext: ");
    string p = GetString();
    int k = 0;
    for (int i = 0; i < strlen(p); i++)
    {
        if(isalpha(p[i]))
        {
            if(isupper(p[i]))
            {
                p[i] = ((p[i]-65)+(key[k % keylen]))%26 + 65;
            }
            else if(islower(p[i]))
            {
                p[i] = ((p[i]-97)+(key[k % keylen]))%26 + 97;
            }
            k++;
        }
        else
        {
            //I need to skip over antyhing that isn't a letter
            p[i] = p[i];
        }
    }
    printf("Ciphertext: %s\n", p);
}
4

1 回答 1

3

第一个for循环有问题。条件是检查i > keylen何时应该检查i < keylen.

同样在计算下一个输出值时,步骤应该是

(p[i]-'A') results in a number between 0 and 25
adding (key[i % keylen]) results in a number between 0 and 50
apply modulo 26 so the number is between 0 and 25 (this is the missing step)
then add 'A' to get the output

注意:避免对字符常量使用硬编码的数字。例如,使用'A'代替 65 和'a'代替 97。

于 2014-04-22T01:36:18.293 回答