凯撒密码加密解密
程序员文章站
2024-03-16 18:07:04
...
加密方法:
凯撒密码需要事先设置一个偏移量值(如:3,4,5等);
然后将自己明文中每个字母加上该偏移量转变为另一字母(如偏移量为3,a字母转变为d字母)。
加密程序:
string encrypt(string mingwen,int k)
{
string miwen;
int i;
for(i=0; i<mingwen.length(); i++)
{
if(mingwen[i]>='a'&&mingwen[i]<='z')
{
miwen += (mingwen[i]-'a'+k)%26+'a';
}
else if(mingwen[i]>='A'&&mingwen[i]<='Z')
{
miwen += (mingwen[i]-'A'+k)%26+'A';
}
else
{
miwen += mingwen[i];
}
}
return miwen;
}
解密时刚好与加密相反,将密文字母减去偏移量即可。
解密程序:
string decrypt(string miwen,int k)
{
string mingwen;
int i;
for(i=0; i<miwen.length(); i++)
{
if(miwen[i]>='a'&&miwen[i]<='z')
{
mingwen += (miwen[i]-'a'+26-k)%26+'a';
}
else if(miwen[i]>='A'&&miwen[i]<='Z')
{
mingwen += (miwen[i]-'A'+26-k)%26+'A';
}
else
{
mingwen+=miwen[i];
}
}
return mingwen;
}
完整程序为:
#include<iostream>
#include<stdio.h>
#include<string>
#include<cstdio>
#include<fstream>
using namespace std;
//加密操作
string encrypt(string mingwen,int k)
{
string miwen;
int i;
for(i=0; i<mingwen.length(); i++)
{
if(mingwen[i]>='a'&&mingwen[i]<='z')
{
miwen += (mingwen[i]-'a'+k)%26+'a';
}
else if(mingwen[i]>='A'&&mingwen[i]<='Z')
{
miwen += (mingwen[i]-'A'+k)%26+'A';
}
else
{
miwen += mingwen[i];
}
}
return miwen;
}
//解密操作
string decrypt(string miwen,int k)
{
string mingwen;
int i;
for(i=0; i<miwen.length(); i++)
{
if(miwen[i]>='a'&&miwen[i]<='z')
{
mingwen += (miwen[i]-'a'+26-k)%26+'a';
}
else if(miwen[i]>='A'&&miwen[i]<='Z')
{
mingwen += (miwen[i]-'A'+26-k)%26+'A';
}
else
{
mingwen+=miwen[i];
}
}
return mingwen;
}
int main()
{
string s;
int i,k;
ifstream fin("in.txt");
ofstream fout("out.txt");
cout<<"选择你需要的操作(1:加密 2:解密 3:**):";
cin>>i;
switch(i)
{
case 1:
cout<<"输入偏移量(小于26):";
cin>>k;
while(getline(fin,s))
{
fout<<encrypt(s,k)<<endl;
}
fin.close();
fout.close();
break;
case 2:
cout<<"输入偏移量(小于26):";
cin>>k;
while(getline(fin,s))
{
fout<<decrypt(s,k)<<endl;
}
fin.close();
fout.close();
break;
case 3:
for(int j=1; j<26; j++)
{
ifstream fin1("in.txt");
ofstream fbr("break.txt",ios::app);
while(getline(fin1,s))
{
fbr<<decrypt(s,j)<<endl;
}
fin1.close();
fbr.close();
}
break;
default :
cout<<"输入不符合规则"<<endl;
}
}
上一篇: Three.js几何对象的组合