C中的仿射密码无法正常工作

时间:2016-02-27 19:31:00

标签: c error-handling cryptography

免责声明:无论如何,它都与Affine Cipher有关。对于任何不了解它的人来说,它是一种加密方法,它使用数学函数Ax + B根据字母表中的字母索引来移动给定明文中的每个字母。

我编写了一个使用Affine Cipher加密和解密给定明文或加密文本的代码。它由以下三个功能组成:

char *encryption(char Plaintext[MAXSIZE], int A, int B);
int modularinverse(int number, int modulo);
char *decryption(char Ciphered[MAXSIZE], int A, int B, int inverse);

在解密功能中涉及我网站的部分。错误计算了大约三到四个字母。

让我们考虑以下明文:" a b c d e"

使用加密功能:

char *encryption(char Plaintext[MAXSIZE], int A, int B) {
    static char Ciphered[MAXSIZE];
    int i;
    int y;
    int index;
    for (i = 0; i < strlen(Plaintext) - 1; i++) {
        if (Plaintext[i] == ' ') {
            Ciphered[i] = ' ';
        } else {
            index = (int)Plaintext[i] - 'a';
            y = (A * index + B) % 26;
            Ciphered[i] = (char)y + 97;
        }
    }
    return Ciphered;
}
它将明文变为:&#34; f m t a h&#34;。这是正确的。

解明明文应该明显地给出:&#34; a b c d e&#34;。但相反,它给出了:&#34; a b c J e&#34;。

char *decryption(char Ciphered[MAXSIZE], int A, int B, int inverse) {
    static char NewPlaintext[MAXSIZE];
    int i;
    unsigned int x;
    int y;
    int index;
    for (i = 0; i < strlen(Ciphered); i++) {
        if (Ciphered[i] == ' ') {
            NewPlaintext[i] = ' ';
        } else {
            index = (int)Ciphered[i] - 'a';
            x = inverse * (index - B) % 26;
            NewPlaintext[i] = (char)x + 97;
        }
    }
    return NewPlaintext;
}

由于我不知道的原因,d字母被错误计算。为每个字符index打印变量inverseBxf m t a h的值将分别返回:

5         15        5         0
12        15        5         1
19        15        5         2
0         15        5         -23
7         15        5         4

第一列表示字母f m t a h的索引。

第二列代表A=7的倒数,即15。 (完全有害,你可以忽略它)。

第三列代表B,它现在是一个常数(你可以忽略它)。

第四列表示x,它是inverse*(index-B) % 26的结果。在此列中为每个数字添加97(ASCII编号&#39; a&#39;)将得到每个字母的ASCII编号。

即0 + 97 = 97这是&#39; a&#39;。结果解密(f)= a。

但是如果你能注意到的话。 x的结果是字母&#39; a&#39;是-23。 -23 + 97 = 74这是ASCII中的J.它应该是100,因为它是d的ASCII码。因此x的结果应该是3,而不是-23。

这次错失计算背后的原因让我感到困惑,我还没有弄明白是什么导致它。

2 个答案:

答案 0 :(得分:1)

您的代码有几个问题:

  • 您在字符串结尾前停止:i<strlen(Plaintext)-1
  • 您不会终止目标字符串。
  • 返回指向静态存储的指针:一次只能加密/解除一个字符串。
  • 取决于值,您可以采用负数的模数,这也是负数。请改用:x = ((inverse * (index - B) % 26) + 26) % 26;

答案 1 :(得分:1)

您的代码几乎没有导致这种奇怪行为的问题;

  1. 如果您正在处理角色,请不要使用public boolean ChoiceOfItem(){ if (bread) this.Choice("bread"); if (meat) this.Choice("meat"); if (lettuce) this.Choice("lettuce"); if (tomato) this.Choice("tomato"); if (carrot) this.Choice("carrot"); return false; } 类型。使用@Override public boolean ChoiceOfItem() { if (ryeBread) this.Choice("ryeBread"); return false; }
  2. 如果int的值为负,则在char句柄中。
  3. 您可以像这样修改decryption()

    x

    我测试了几个条目并且工作正常。

    希望这有帮助。