C语言实现替代密码算法
1、创建文件:tihuanmima.c
2、编辑源代码;代码如下
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char plain[20];
char cipher[20];
int k;
int jiami(){
printf("请输入明文:");
scanf("%s",plain);
printf("请输入密钥(即k的值):");
scanf("%d",&k);
printf("明文是:%s\n",plain);
printf("密文是:");
for(int i=0;i<strlen(plain);i++){
if(plain[i]>=97){
char temp=plain[i];
temp=(temp+k)%122;
if(temp>0&&temp<=k)
printf("%c",temp+96);
if(temp==0)
printf("%c",temp+122);
else
printf("%c",temp);
}else{
char temp=plain[i];
temp=(temp+k)%90;
if(temp>0&&temp<=k)
printf("%c",temp+64);
if(temp=0)
temp=122;
else
printf("%c",temp);
}
}
printf("\n");
return 0;
}
int jiemi(){
printf("请输入密文:");
scanf("%s",cipher);
printf("请输入密钥(即k的值):");
scanf("%d",&k);
printf("密文是:%s\n",cipher);
printf("明文是:");
for(int i=0;i<strlen(cipher);i++){
char temp=cipher[i];
temp=temp-k;
if(temp<97)
printf("%c",123-(97-temp));
else
printf("%c",temp);
}
printf("\n");
return 0;
}
int main(){
int a;
while(1){
printf("按1加密,按2解密,按3退出");
scanf("%d",&a);
if(a==1)
jiami();
if(a==2)
jiemi();
if(a==3){
exit(0);
}
}
}
3、使用gcc进行编译,然后用ls命令找到a.out(这个是gcc自己生成的可执行文件)并且执行