【问题标题】:Vigenere cipher in C wraparoundC 环绕中的 Vigenere 密码
【发布时间】:2016-02-19 14:09:42
【问题描述】:

我在编写涉及编写 Vigenere 密码的作业的代码的最后一部分时遇到问题。加密部分工作正常,但我无法弄清楚如何重复加密字/关键字。因此,如果需要加密的消息小于或等于关键字,则它可以正常工作,否则它会输出另外几个字符,这些字符看起来是加密的,但实际上并非如此。

这是目前为止的代码:

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

int main(int argc, string argv[])
{
    if (argc != 2)
    {
        printf("YELL!\n");
        return 1;
    }
    //check if the number of command line arguments is correct, if not, YELL!

    string keyword = (argv[1]);
    //get keyword

    for (int j = 0, n = strlen(keyword); j < n; j++)
    {
    if(!isalpha(keyword[j]))
        {   
        printf("YELL!\n");
        return 1;
        }
    }
    //check if the keyword is only alphabetical, if not, YELL!

    string message = GetString();
    //get plaintext

    for (int j = 0, n = strlen(keyword); j < n; j++)
    {
        if (isupper(keyword[j]))
        {
            keyword[j] = (keyword[j] - 'A');
        }

        if (islower(keyword[j]))
        {
            keyword[j] = (keyword[j] - 'a');
        }
    }
    //this is to get the numerical values from the ascii values of the keyword.

    for (int i = 0, j = 0, n = strlen(message); i < n; i++, j++)
    //counting through the message & the cypher
    {
        if (isalpha(message[i]))
        {
            if (isupper(message[i]))
            {
            message[i] = (((message[i] - 'A') + keyword[j]) % 26 + 'A');
            }

            if (islower(message[i]))
            {
            message[i] = (((message[i] - 'a') + keyword[j]) % 26 + 'a');
            }

            //adding a keyword value [j] to message [i] and converting back to ascii value, 
            //individually for upper and lowercase characters.
        }
    printf("%c", message[i]);
    } 
}

这可能是一个简单的解决方案,但我就是想不通。任何帮助将不胜感激!

【问题讨论】:

    标签: c encryption cs50 vigenere


    【解决方案1】:

    加密对您有用,真是奇迹。我认为不是,因为您的循环显然可能会使 j 超过关键字长度,然后 keyword[j] 将超出范围并表现出未定义的行为。您只需在消息长度上迭代i 并使用keyword[i % strlen(keyword)] 索引关键字,这样索引将从0 循环到keyword 的长度减一。

    【讨论】:

      猜你喜欢
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多