1 题目
功能:恺撒加密描述:利用凯撒密码进行加密
2 凯撒密码
维基百科对凯撒密码的解释:https://zh.wikipedia.org/wiki/%E5%87%B1%E6%92%92%E5%AF%86%E7%A2%BC
凯撒密码是一种替换加密技术,明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。例如,当偏移量是3的时候,所有的字母A将被替换成D,B变成E,以此类推
例如,当偏移量是左移3的时候(解密时的密钥就是3):
明文字母表:ABCDEFGHIJKLMNOPQRSTUVWXYZ
密文字母表:DEFGHIJKLMNOPQRSTUVWXYZABC
3 代码
# include <stdio.h>
# include <string.h>
/**
功能:恺撒加密
描述:利用凯撒密码进行加密
**/
voidencode(charstr[],intn) {
charc;
inti;
for(i=0;i<strlen(str);i++) {
c=str[i];
if(c>='a'&&c<='z')
if(c+n%26<='z')
str[i]=(char)(c+n%26);
else
str[i]=(char)('a'+((n-('z'-c)-1)%26));
elseif(c>='A'&&c<='Z')
if(c+n%26<='Z')
str[i]=(char)(c+n%26);
else
str[i]=(char)('A'+((n-('Z'-c)-1)%26));
else
str[i]=c;
}
printf("\nout:");
puts(str);
}
voiddecode(charstr[],intn) {
charc;
inti;
for(i=0;i<strlen(str);i++) {
c=str[i];
if(c>='a'&&c<='z')
if(c-n%26>='a')
str[i]=(char)(c-n%26);
else
str[i]=(char)('z'-(n-(c-'a')-1)%26);
elseif(c>='A'&&c<='Z')
if(c-n%26>='A')
str[i]=(char)(c-n%26);
else
str[i]=(char)('Z'-(n-(c-'A')-1)%26);
else
str[i]=c;
}
printf("\nout:");
puts(str);
}
intmain(intargc,charconst*argv[]) {
voidencode(charstr[],intn);
voiddecode(charstr[],intn);
//char str[]="abcdef";
charstr[20];
intk=0,n=0,i=1;
printf("\nPlease input strings:");
scanf("%s",str);
printf("\n1:Encryption");
printf("\n2:Decryption");
printf("\n3:Violent Crack");
printf("\nPlease choose:");
scanf("%d",&k);
if(k==1) {
printf("\nPlease input number:");
scanf("\n%d",&n);
encode(str,n);
}
elseif(k==2) {
printf("\nPlease input number:");
scanf("%d",&n);
decode(str,n);
}
elseif(k==3) {
for(i=1;i<=25;i++) {
printf("%d ",i);
decode(str,1);
}
}
}
示例结果:
$ gccex080.c-odemo
$ ./demo
Please input strings:python
1:Encryption
2:Decryption
3:Violent Crack
Please choose:1
Please input number:1
out:qzuipo
该例子中有以下三种选择,结合上述对于凯撒密码的原理,试着进行理解
Encryption
Decryption
Violent Crack