1 题目
功能:恺撒加密 描述:利用凯撒密码进行加密
2 凯撒密码
维基百科对凯撒密码的解释:zh.wikipedia.org/wiki/%E5%87…
凯撒密码是一种替换加密技术,明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。例如,当偏移量是3的时候,所有的字母A将被替换成D,B变成E,以此类推
例如,当偏移量是左移3的时候(解密时的密钥就是3):
明文字母表:ABCDEFGHIJKLMNOPQRSTUVWXYZ
密文字母表:DEFGHIJKLMNOPQRSTUVWXYZABC
3 代码
# include <stdio.h>
# include <string.h>
/**
功能:恺撒加密
描述:利用凯撒密码进行加密
**/
void encode(char str[], int n) {
char c;
int i;
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));
else 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));
else
str[i] = c;
}
printf("\nout:");
puts(str);
}
void decode(char str[], int n) {
char c;
int i;
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);
else 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);
else
str[i] = c;
}
printf("\nout:");
puts(str);
}
int main(int argc, char const *argv[]) {
void encode(char str[], int n);
void decode(char str[], int n);
//char str[]="abcdef";
char str[20];
int k = 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);
}
else if (k == 2) {
printf("\nPlease input number:");
scanf("%d", &n);
decode(str, n);
}
else if (k == 3) {
for (i = 1; i <= 25; i++) {
printf("%d ", i);
decode(str, 1);
}
}
}
示例结果:
$ gcc ex080.c -o demo
$ ./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