// 恺撒加密解密小程序
// 作者:kvew
//
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
void kaiser(int n){
unsigned char ch;
FILE *fp1,*fp2;
if((fp1=fopen("a.txt","r"))==NULL){ //以读的方式打开文件a.txt
printf("can not open the file a.txt!\n");
exit(0);
}
if((fp2=fopen("kaiser.txt","w"))==NULL){ //以写的方式打开b.txt
printf("can not open the file b.txt!\n");
exit(0);
}
while(!feof(fp1)){
ch = fgetc(fp1);
if(ch>=65&&ch<=90){ //如果是大写字母
ch = ch + n; //移位
if(ch>=91) //移位后仍然在大写字母集中,直接返回
ch = ch%90+64; //超出则转换下
}
else if(ch>=97&&ch<=122){ //如果是小写字母
ch = ch + n; //移位
if(ch>=123) //移位后仍然在小写字母集,直接返回
ch = ch%122+96; //超出则转换下
}
fputc(ch,fp2); //如果是其他字符,则不加密照常输出
}
if(fclose(fp1)){ //关闭文件a.txt
printf("Can not close the file!\n");
}
if(fclose(fp2)){ //关闭文件kaiser.txt
printf("Can not close the file!\n");
}
}
void break_kaiser(){
int i,count,k;
int key;
int num[26] = {0}; //初始化数组,该数组用来统计密文中各个字母的出现次数
unsigned char ch,ch_b; // num[0]-----num[25]对应字母A--Z
FILE *fp1,*fp2;
if((fp1=fopen("kaiser.txt","r"))==NULL){ //以读的方式打开文件a.txt
printf("can not open the file a.txt!\n");
exit(0);
}
if((fp2=fopen("out.txt","w"))==NULL){ //以写的方式打开b.txt
printf("can not open the file b.txt!\n");
exit(0);
}
while(!feof(fp1)){
ch = fgetc(fp1);
if(ch>=65&&ch<=90){
num[ch-65]++;
}
else if(ch>=97&&ch<=122){
num[ch-97]++;
}
}
if(fclose(fp1)){ //关闭目标文件a.txt
printf("Can not close the file!\n");
}
count = num[0];
for(i=0;i<26;i++){
printf("the num[%d] is %d\n",i,num); //打印出统计信息
if(count<num) {
count = num;
k = i; //记录下最大值的下标
}
}
printf("\n\nthe max is %d and its index is %d\n",count,k);
ch_b = 65 + k; // 记录下出现次数最多的字符,以大写方式记录
printf("the ch_b is %d\n",ch_b);
key = ch_b - 69; //和 E 值相减,计算出key
if(key<0)
key = 26 + key;
printf("the key is: %d\n",key);
if((fp1=fopen("kaiser.txt","r"))==NULL){ //再次以读的方式打开文件a.txt
printf("can not open the file a.txt!\n");
exit(0);
}
while(!feof(fp1)){ //如果没有读到文件结尾,那么继续读取
ch = fgetc(fp1);
if(ch>=65&&ch<=90){
ch = ch - key;
if(ch < 65)
ch = 90 - (64 - ch);
}
if(ch>=97&&ch<=122){
ch = ch - key;
if(ch < 97)
ch = 122 - (96 - ch);
}
fputc(ch,fp2);
}
if(fclose(fp2)){ //关闭文件b.txt
printf("Can not close the file!\n");
}
}
int main(){
int n;
printf("***********************************************************\n");
printf("* *\n");
printf("* this program will encrypt the file a.txt to kaiser.txt! *\n");
printf("* and then decrypt kaiser.txt to out.txt *\n");
printf("* *\n");
printf("***********************************************************\n\n");
printf("\nplease input the key number (0--25):\n");
scanf("%d",&n);
kaiser(n);
printf("encrypted success!\n\n");
// printf("密文中各字母出现次数的统计信息入下:\n");
break_kaiser();
printf("creaked success!\n");
return 0;
}
|