失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 凯撒密码c++语言程序 凯撒密码(加密与解密)

凯撒密码c++语言程序 凯撒密码(加密与解密)

时间:2022-09-22 08:28:56

相关推荐

凯撒密码c++语言程序 凯撒密码(加密与解密)

下面是编程之家 通过网络收集整理的代码片段。

编程之家小编现在分享给大家,也给大家做个参考。

/************************************************************************/

/*caeser.c

/* 凯撒密码是把明文字符按照相同的位移量向后移动

/*比如明文can,位移量为3,密文为fdq

/*本程序仅对英文字母和数字有效

/*使用时将文件置于caeser.c同目录下,密文默认名字为cipher.txt

/************************************************************************/

#include

#include

#define ITEM 2

void 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]();

else

break;

}

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);

}

else

fputc(ch,outfile);

ch=fgetc(infile);

}

if(fclose(infile)||fclose(outfile))

printf("File cannot close!\n");

else

printf("加密成功");

}

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);

ch=fgetc(infile);

}

if(fclose(infile)||fclose(outfile))

printf("File cannot close!\n");

else

printf("解密成功");

}

以上是编程之家()为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

总结

以上是编程之家为你收集整理的凯撒密码(加密与解密)全部内容,希望文章能够帮你解决凯撒密码(加密与解密)所遇到的程序开发问题。

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。

小编个人微信号 jb51ccc

喜欢与人分享编程技术与工作经验,欢迎加入编程之家官方交流群!

如果觉得《凯撒密码c++语言程序 凯撒密码(加密与解密)》对你有帮助,请点赞、收藏,并留下你的观点哦!

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