qq_24670555 于 2016.09.23 21:48 提问

//实现维吉尼亚密码的算法

# include

char plaintext[100],key[20],ciphertext[100],decry_plaintext[100];
void encryption();//加密函数
void decryption();//解密函数

void encryption()
{
int length_plain,length_cipher,i = 0,j = 0;
length_plain = strlen(plaintext);//明文长度
length_cipher = strlen(ciphertext);//密文长度
if(length_plain > length_cipher)//明文长度大于密钥长度
{
for(i = 0;i < length_plain;i++)
{
ciphertext[i] = (plaintext[i] + key[j]) % 26 + 97 - 32;//小写字母转化为大写字母
printf("%c",ciphertext[i]);
j++;
if(j >= length_cipher){
j = 0;
}
}
}
else
{
for(i = 0;i < length_plain;i++)
{
ciphertext[i] = (plaintext[i] + key[j]) % 26 + 97 - 32;
printf("%c",ciphertext[i]);
j++;
}
}
printf("\n");
}

void decryption()
{
int length_plain,length_cipher,i = 0,j = 0;
length_plain = strlen(plaintext);
length_cipher = strlen(ciphertext);
if(length_plain > length_cipher)
{
for(i = 0;i < length_plain;i++)
{
decry_plaintext[i] = (ciphertext[i] - key[j]) % 26 + 97;
printf("%c",decry_plaintext[i]);
j++;
if(j >= length_plain){
j = 0;
}
}
}
else
{
for(i = 0;i < length_cipher;i++)
{
decry_plaintext[i] = (ciphertext[i] - key[j]) % 26 + 97;
printf("%c",decry_plaintext[i]);
j++;
}
}
printf("\n");
}

int main()
{
gets(plaintext);//输入明文
gets(key);//输入密钥
puts(ciphertext);
encryption();