c - 'De-Vigenere' 程序中带有模运算符的负数

标签 c encryption vigenere

我正在制作一个解密维吉尼亚密码的程序。用户只能给出字母键。

for (int i = 0, counter = strlen(text); i < counter; i++)
    {
        // prints non-alphabetical characters straight away
        if (!isalpha(text[i]))
        {
            printf("%c", text[i]);
        }

        else
        {
            // for index of key
            index = meta % strlen(key);

            if (islower(text[i]))
            {
                // separate cases depending upon case of key
                if (islower(key[index]))
                {
                    printf("%c", (((text[i] - 97) - (key[index] - 97)) % 26) + 97);
                }
                else
                {
                    printf("%c", (((text[i] - 97) - (key[index] - 65)) % 26) + 97);
                }
            }

            else
            {
                if (islower(key[index]))
                {
                    printf("%d", (((text[i] - 65) - (key[index] - 97)) % 26) + 65); 
                }
                else
                {
                    printf("%c", (((text[i] - 65) - (key[index] - 65)) % 26) + 65);
                }
            }
            // incrementing for next key alphabet
            meta++;
        }

维杰内尔:

  • 输入:我的名字

  • 键:qwerty

  • 输出:CuRrfc

德维杰内尔:

  • 输入:CuRrfc
  • 键:qwerty
  • 预期输出:MyName
  • 给定输出:3_NaSK

如何修复它?

最佳答案

问题在于模运算符处理负数的方式。

对于某些字符,您会得到负值,然后模数运算会返回负值。您需要一个 [0, 25] 范围内的值。

您可以通过在取模之前添加 26 来解决此问题。

                printf("%c", (((text[i] - 97) - (key[index] - 97)) % 26) + 97);

会变成

                printf("%c", (((text[i] - 97) - (key[index] - 97) + 26) % 26) + 97);

以同样的方式更改所有四行。

关于c - 'De-Vigenere' 程序中带有模运算符的负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37852668/

相关文章:

c - 维吉尼亚加密

c - 了解由于 getchar 而导致的 c 循环

java - 如何使用具有加密属性的 Google Guice?

安卓.security.KeyStoreException : Incompatible purpose

c++ - 如何在 Crypto++ 中加载 Base64 RSA key

c - Vigenere 密码陷入无限循环

c - C中的Vigenere密码

c - 除了与函数指针一起使用之外,是否还有在 C 中对函数进行类型定义的目的?

c - 在c中的二维数组中获取字符串输入

c - gdb 没有正确打印字符串值