900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 凯撒密码(加密与解密)

凯撒密码(加密与解密)

时间:2020-10-21 14:02:51

相关推荐

凯撒密码(加密与解密)

/************************************************************************//*caeser.c/* 凯撒密码是把明文字符按照相同的位移量向后移动/*比如明文can,位移量为3,密文为fdq/*本程序仅对英文字母和数字有效/*使用时将文件置于caeser.c同目录下,密文默认名字为cipher.txt/************************************************************************/#include<stdio.h>#include<stdlib.h>#define ITEM 2void encipher();void decipher();int main(){int flag;void (*menu[ITEM])()={encipher,decipher};printf("加密文件——1\n");printf("解密文件——2\n");printf("退出程序——0\n");while(1){scanf("%d",&flag);if(!flag)exit(1);else if(flag==1||flag==2)menu[flag-1]();elsebreak;}return 0;}void encipher(){int key;char ch,c;char file_name[50];FILE *infile,*outfile;printf("输入欲加密文件名:");scanf("%s",file_name);printf("输入加密密钥:");scanf("%d",&key);if((infile=fopen(file_name,"r"))==NULL){printf("Cannot open file!\n");exit(1);}if((outfile=fopen("cipher.txt","w"))==NULL){printf("Cannot open file!\n");exit(1);}ch=fgetc(infile);while(!feof(infile)){if(ch>=48&&ch<=57)//数字加密{c=((ch-48)+key)%10;fputc((char)(c+48),outfile);}else if(ch>=65&&ch<=90)//大写英文字母加密{c=((ch-65)+key)%26;fputc((char)(c+65),outfile);}else if(ch>=97&&ch<=122)//小写英文字母加密{c=((ch-97)+key)%26;fputc((char)(c+97),outfile);}elsefputc(ch,outfile);ch=fgetc(infile);}if(fclose(infile)||fclose(outfile))printf("File cannot close!\n");elseprintf("加密成功");}void decipher(){int key;char ch,c;FILE *infile,*outfile;printf("输入解密密钥:");scanf("%d",&key);if((infile=fopen("cipher.txt","r"))==NULL){printf("Cannot open file!\n");exit(1);}if((outfile=fopen("a.txt","w"))==NULL){printf("Cannot open file!\n");exit(1);}ch=fgetc(infile);while(!feof(infile)){if(ch>=48&&ch<=57)//数字解密{c=((ch-48)-key+10)%10;//此处+10是防止,c==负数fputc((c+48),outfile);}else if(ch>=65&&ch<=90)//大写英文字母解密{c=((ch-65)-key+26)%26;fputc((char)(c+65),outfile);}else if(ch>=97&&ch<=122)//小写英文字母解密{c=((ch-97)-key+26)%26;fputc((char)(c+97),outfile);}elsefputc(ch,outfile);ch=fgetc(infile);}if(fclose(infile)||fclose(outfile))printf("File cannot close!\n");elseprintf("解密成功");}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。