凯撒密码
在密码学中,恺撒密码(英语:Caesar cipher),或称恺撒加密、恺撒变换、变换加密,是一种最简单且最广为人知的加密技术。它是一种替换加密的技术,属于简单的古典密码。明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。例如,当偏移量是3的时候,所有的字母A将被替换成D,B变成E,以此类推。例如:当明文为i am fine时,密文为:enif ma i。这个加密方法是以罗马共和时期恺撒的名字命名的,当年恺撒曾用此方法与其将军们进行联系。
当向右偏移量为3时,C语言代码如下:
#include<stdio.h>
void main()
{
int x=1;
int a,i;
char s[5];
while(x==1)
{
printf("请选择您要进行的操作:1.加密 2.解密 3.结束操作\n");
scanf("%d",&a);
switch(a)
{
case 1:
{
printf("请输入需要加密的信息:");
scanf("%s",s);
for(i=0;i<=4;i++)
{
s[i]=(s[i]-97+3)%26+97;
}
printf("密文为:%s\n",s);
break;//加上break才可以循环
}
case 2:
{
printf("请输入需要解密的信息:");
scanf("%s",s);
for(i=0;i<=4;i++)
{
s[i]=((s[i]-97-3)%26+26)%26+97;
}
printf("明文为:%s\n",s);
break;
}
case 3:
{
x=0;
}
}
}
}
偏移量不一定为3,也可以是其他的数字。如果偏移量为K时,采用模块化设计思想,则代码如下:
#include<stdio.h>
#include <string.h>
#include<stdlib.h>
#define MAX 100
char ciphertext[MAX]; //密文
char plaintext[MAX]; //明文
int K;
//加密
void Encryption()
{
printf("\n请输入明文:");
gets(plaintext);
printf("\n密文为:");
for(int i=0; plaintext[i] != '\0'; i++)
{
if(plaintext[i] >= 'A' && plaintext[i] <= 'Z')
{
ciphertext[i] = (plaintext[i] - 'A' + K) % 26 + 'A';
}
else if (plaintext[i] >= 'a' && plaintext[i] <= 'z')
{
ciphertext[i]=(plaintext[i] - 'a' + K) % 26 + 'a';
}
else
ciphertext[i] = plaintext[i];
printf("%c",ciphertext[i]);
}
printf("\n");
}
//解密
void Decryption()
{
printf("\n请输入密文:");
gets(ciphertext);
printf("\n明文为:");
for(int i=0; ciphertext[i] != '\0'; i++)
{
if(ciphertext[i] >= 'A' && ciphertext[i] <= 'Z')
{
plaintext[i] = ((ciphertext[i] - 'A' - K) % 26 + 26)%26 + 'A';
}
else if (ciphertext[i] >= 'a' && ciphertext[i] <= 'z')
{
plaintext[i]=((ciphertext[i] - 'a' - K) % 26 + 26)%26 + 'a';
}
else
plaintext[i] = ciphertext[i];
printf("%c",plaintext[i]);
}
printf("\n");
}
void main()
{
int n,flag=1;
printf("密钥为:");
scanf("%d",&K);
while(flag)
{
printf("\n请选择(1:加密,2:解密,3:退出):");
scanf("%d",&n);
getchar();
switch(n)
{
case 1:
Encryption();
break;
case 2:
Decryption();
break;
case 3:exit(0);
}
}
}