1. 背景介绍
维吉利亚密码
维吉尼亚密码引入了“密钥”的概念,即根据密钥来决定用哪一行的密表来进行替换,以此来对抗字频统计。假如以上面第一行代表明文字母,左面第一列代表密钥字母,对如下明文加密:
TO BE OR NOT TO BE THAT IS THEQUESTION
当选定RELATIONS作为密钥时,加密过程是:明文一个字母为T,第一个密钥字母为R,因此可以找到在R行中代替T的为K,依此类推,得出对应关系如下:
密钥:RELAT IONSR ELATI ONSRE LATIO NSREL
明文:TOBEO RNOTT OBETH ATIST HEQUE STION
密文:KSMEH ZBBLK SMEMP OGAJX SEJCS FLZSY
2. 需求分析
程序有两种模式:加密模式和解密模式。
加密模式下,提供原文和密钥,即可得到密文;相反,在解密模式下提供密文和密钥即可得到原文。
3. 源代码
代码在Codeblock上运行正常。
密钥用循环链表存储。
#include<stdio.h>
#include<ctype.h>
#define key_size 30
#define name_size 100
#define title "------------------------Life is a Fight-----------------------------------"
typedef struct NODE{
int a;
struct NODE* next;
} node;
node* CreateKey(char* key)
{
node* head, *p;
head=(node*)malloc(sizeof(node));
p=head;
while((*key)!='\0')
{
p->next=malloc(sizeof(node));
p=p->next;
p->a=tolower(*key)-'a';
p->next=head->next;
key++;
}
return head;
}
void Encryption(FILE* infp, node* head)
{
FILE* outfp;
char ori,enc;
node* p;
p=head->next;
outfp=fopen("Encryption.txt","w");
while(!feof(infp))
{
ori=tolower(fgetc(infp));
if(ori>='a'&&ori<='z')
{
enc=97+(ori-97+p->a)%26;
p=p->next;
}
else
enc=ori;
fprintf(outfp,"%c",enc);
}
fclose(outfp);
}
void Decryption(FILE* infp, node* head)
{
FILE* outfp;
char enc,ori;
node* p;
p=head->next;
outfp=fopen("Decryption.txt","w");
while(!feof(infp))
{
enc=tolower(fgetc(infp));
if(enc>='a'&&enc<='z')
{
ori=97+(enc-97+26-p->a)%26;
p=p->next;
}
else
ori=enc;
fprintf(outfp,"%c",ori);
}
fclose(outfp);
}
int main(void)
{
char key[key_size];
node* h;
char mode;
char name[name_size];
FILE* fp;
printf("%s\n",title);
while(1)
{
printf("\n\n\nPlease choose mode:\n");
printf("E---Encryption Mode D---Decryption Mode Q---Quit\n");
scanf("%c",&mode);
if(mode=='e'||mode=='E')
{
printf("Please enter the file name need to be encrypted:");
scanf("%s",name);
fp=fopen(name,"r");
while(fp==NULL)
{
fflush(stdin);
printf("ERR:please re-enter the file name need to be :");
scanf("%s",name);
fp=fopen(name,"r");
}
printf("Please enter your key word:");
fflush(stdin);
gets(key);
h=CreateKey(key);
Encryption(fp,h);
printf("The encryption has been finished.\n");
fclose(fp);
}
else if(mode=='d'||mode=='D')
{
printf("Please enter the file name need to be encrypted:");
scanf("%s",name);
fp=fopen(name,"r");
while(fp==NULL)
{
fflush(stdin);
printf("ERR:please re-enter the file name need to be :");
scanf("%s",name);
fp=fopen(name,"r");
}
printf("Please enter your key word:");
fflush(stdin);
gets(key);
h=CreateKey(key);
Decryption(fp,h);
printf("The decryption has been finished.\n");
fclose(fp);
}
else if(mode=='q'||mode=='Q')
return;
else
printf("Err:please select correct mode.");
fflush(stdin);
}
return 0;
}