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

免责声明:无论以下内容如何,​​都与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);

与我有关的部分位于解密功能中。大约错失了三个或四个字母。

让我们考虑以下纯文本:“ abcd 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;
}

它将纯文本转换为:“ fmta h”。哪个是对的。

解密明文显然应该给出:“ abcd e”。但相反,它给出:“ abc J e”。

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的值inverse对于每个字符将分别返回以下内容:Bxf 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码“ a”)将得出每个字母的ASCII码。

即0 + 97 = 97,即“ a”。结果,解密(f)= a。

但是,如果您可以注意到。x表示字母“ a”的结果为-23。-23 + 97 = 74,它是ASCII中的J。应该是100,因为它是d的ASCII码。因此,x的结果应该是3,而不是-23。

这种错误计算背后的原因让我很困惑,我还没有弄清楚是什么原因造成的。

Sudipta Kumar Sahoo

您的代码很少有导致这种奇怪行为的问题。

  1. int如果要处理字符,请不要使用文字。采用char
  2. decryption()如果的值为x句柄中

您可以decryption()像这样修改您的内容

char *decryption(char Ciphered[MAXSIZE],int A, int B, int inverse)
{
    static char NewPlaintext[MAXSIZE];
    char x;
    char index;
    for(int i=0;i<strlen(Ciphered);i++)
    {
        if(Ciphered[i]==' ')
        {
            NewPlaintext[i]=' ';
        }
        else
        {
            index=(int)Ciphered[i] - 'a';
            x=inverse*(index-B) % 26;
            if(x < 0)
            {
                // add 26 to take care of negative values; since you are using %
                x += 26;
            }
            NewPlaintext[i]=(char)x+97;
        }
    }
    return NewPlaintext;
}

我测试了它几个条目,它工作正常。

希望这可以帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章