C中的密文,如何重复关键字符

时间:2015-06-04 10:38:36

标签: c encryption vigenere

  • 解释 通过将明文和密钥的相应字符“加”在一起,从明文生成密文。如果明文比密钥短,则只使用一些密钥。同样,如果明文比密钥短,则密钥将被多次使用。

    例如,使用“CAT”键对明文“HELLO”进行编码:

明文:HELLO

Key:CATCA

密文:KFFOP

使用键“FIDO”对明文“DOG”进行编码:

明文:DOG

键:FID

密文:JXK

要一起添加两个字母,请使用以下约定:A = 1,B = 2,...,Z = 26。如果两个字母的总和大于26,则从总和中减去26。例如:A + E = 1 + 5 = 6 = F,D + X = 4 + 24 = 28 = 2 = B.

  • 现在我的代码问题在于,如果关键字符较少,我无法重复关键字符以进一步编码纯文本,如何重复关键字符,那么可以进一步编码吗?

帮助我们。

这是我的代码:

#include<stdio.h>
    #include<string.h>
    int main()
        {
            char str[100],k[50],str1[100];
            int i,n;
            gets(str);// Input plain text. 
            gets(str1);//Input key.
             for(i=0;str[i]!='\0';i++)
                    {
                         n=(str[i]-65+1)+(str1[i]-65+1);//Extracting the numerical position and adding them.
                         if(n>26) //if numerical value exceeds 26 then subtracting 26 from it and getting the numerical value.
                          {
                             n=n-26;
                          }
                         str[i]=n+64;//storing the ciphered character.
                    }

              for(i=0;str[i]!='\0';i++)//printing the ciphered characters.
              printf("%c",str[i]);
              return 0;

        }

3 个答案:

答案 0 :(得分:1)

在编写循环时,用于索引键的变量应重置为0以重复键(如果原始文本长度较大)。

for(int i = 0, j = 0; input[i] != '\0'; ++i, ++j) {
    new_char = (input[i] - 64) + (key[j] - 64);
    new_char = adjust(new_char);
    cipher[i] = new_char + 64 ;
    if(j == (key_length - 2)) // if j is at the end, excluding null character, then make j = -1, which gets incremented to j = 0 in the next loop iteration
        j = -1;
}

还可以使用fgets进行字符串输入,不要使用gets。可以使用%s格式说明符打印C中的字符串,而无需编写显式循环来输出字符。为此,将密码字符数组的最后一个元素作为\0字符。

答案 1 :(得分:1)

您可以使用另一个循环变量,每次达到其长度时,使键的索引为0。在这种情况下我使用了变量j。试试这段代码:

#include<stdio.h>
#include<string.h>
int main()
    {
        char str[100],k[50],str1[100];
        int i,n;
        gets(str);// Input plain text. 
        gets(str1);//Input key.
        int lenk=strlen(str1),j;   //calculate length of key
         for(i=0,j=0;str[i]!='\0';i++,j++)
    {
         if(j==lenk) j=j-lenk;      //make j=0
         n=(str[i]-65+1)+(str1[j]-65+1);    // add str1[j] instead
         if(n>26) 
          {
             n=n-26;
          }
         str[i]=n+64;//storing the ciphered character.

    }

          for(i=0;str[i]!='\0';i++)
          printf("%c",str[i]);
          return 0;

    }

请注意,这仅适用于大写字母,您必须更改您的代码以获得小写字母

答案 2 :(得分:1)

您也可以使用模运算来重复字符。

for(i=0;str[i]='\0';i++)
{
    n = (str[i]-65+1 + (str1[i % lenk]-65 +1);    
    n = (n % 26) + 1;
    str[i] = n+64;
    //storing the ciphered character.

}

表达式i % 26自动将值0到25旋转。

同样可以应用于将n从1旋转到26。