c - C 语言的维吉尼亚密码封装

标签 c encryption cs50 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]);
    } 
}

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

最佳答案

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

关于c - C 语言的维吉尼亚密码封装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35507308/

相关文章:

棋盘问题

.net - 如何使用 LINQ to XML 读取/写入加密的 XML 文件?

encryption - Travis-CI 需要什么来解密我的 fork 上的安全变量?

algorithm - 这是哪种密码算法?

c - 为什么此代码中会产生 6 个 # 标记?

c - 对于 <stdbool.h> 中的 bool 类型,eclipse cdt 格式化程序的行为不正确

c - 线程执行问题

c - 将每个字母移动多个位置后,如何按字母顺序将 z 换成 a,将 Z 换成 A?

Cs50 棕褐色将图像从正常转换为棕褐色的问题

将当前时间与给定时间进行比较