vigenere cipher c language



我试图用C语言制作一个vigenere密码。输入仅是字母顺序的字符(A-> Z)。

目前,我的问题是输出仅显示4个字符,并在字母内输出奇怪的字符。我已经创建了IF语句来防止这种情况,但似乎它们不起作用。有建议吗?

#include <stdio.h>

int main(){
    int i=0;
//Vigenere Cipher-- keyword is "apple"
//a = 1  value shift
//p = 16 value shift
//p = 16 value shift
//l = 17 value shift
//e = 5  value shift
 //cleaning out string array
 char guy[100];
printf("Enter the plain text: ");
fgets(guy, 100, stdin);//takes user's input
while (guy[i] != ''){ //while loop that runs until it reaches the end of the string
    if ((i%5==0) || i==0){ //checks to see which character it is in the string, for instance the numbers 0,5,10,15,20 should all be added by 1
    guy[i] = guy[i]+1;
    if (guy[i]>'z' && guy[i]<'A'){
            guy[i]-25;
    }
    if (guy[i]>'Z' && guy[i]>'A'){
        guy[i]-25;
    }
    }
    if (((i-1)%5==0) || i==1){ //all numbers that are second in the key word 'apple', such as 1,6,11,16
        guy[i]=guy[i]+16;
        if (guy[i]>'z' && guy[i]<'A'){
            guy[i]-25;
        }
        if (guy[i]>'Z' && guy[i]>'A'){
            guy[i]-25;
        }
    }
    if (((i-2)%5==0) || i==2){// all numbers that are third to the key word 'apple' , such as 2,7,12,17,22
        guy[i]=guy[i]+16;
        if (guy[i]>'z'&& guy[i]<'A'){
            guy[i]-25;
        }
        if (guy[i]>'Z'&& guy[i]>'A'){
            guy[i]-25;
        }
    }
    if(((i-3)%5==0) || i==3){// all numbers that are fourth to the key word 'apple', such as 3,8,13,18
        guy[i]=guy[i]+17;
        if (guy[i]>'z'&&guy[i]<'A'){//takes care of z
            guy[i]-25;
    }
        if (guy[i]>'Z' && guy[i]>'A'){//takes care of Z
            guy[i]-25;
        }
    }
    if(((i-4)%5==0) || i==4){// all numbers that are fifth in the key word 'apple', such as 4,9,14,19
        guy[i]=guy[i]+5;
        if (guy[i]>'z'&& guy[i]<'A'){
            guy[i]-25;
        }
        if (guy[i]>'Z' && guy[i]>'A'){
            guy[i]-25;
        }
    }
    else {
    i++;
    }
    }
printf("Encrypted text is: %sn",guy);
}

具有为您加密加密的函数encrypt_char()。

void encrypt_char(char *character, unsigned int offset)
{
    if('a' <= *character && 'z' >= *character)
    {
        *character = ((*character + offset - 'a') % 26) + 'a';
    } 
    else if('A' <= *character && 'Z' >= *character)
    {
        *character = ((*character + offset - 'A') % 26) + 'A';
    }
}

用您的偏移值调用它。

if (i%5==0){
    encrypt_char(&(guy[i]), 1);
} else if ((i-1)%5==0){
     encrypt_char(&(guy[i]), 16);
} else...

而不是放弃整个游戏,这是基于我的评论的一些代码(未经测试!):

char encrypt_char(char plain_text, char key)
{
    char offset = tolower(key) - 'a' + 1;
    if (islower(plain_text))
        return (plain_text - 'a' + 1 + offset) % 26 + 'a';
    else if (isupper(plain_text))
        return (plain_text - 'A' + 1 + offset) % 26 + 'A';
    else
        return plain_text;
}

这可能会沿途某个地方,因此请进行有趣的调试!

最新更新