古典密码之单表代替密码Cpp源码
单表代替密码是一种固定明文字符集到密文字符集的映射,是古代密码编码技术中的一种比较简单的编码技术,属于简单的代换密码,即一个字符用另一个字符进行代换。
单表代替密码中比较典型的密码算法是凯撒(Caesar)密码,其本质就是构造不同字母的映射表,通过映射表来完成对数据的加密和解密。
单表代替密码算法的实现过程主要包括两部分内容,一部分是加密过程,另一部分是解密过程,下面的实现过程就是针对历史上有名的凯撒密码来完成的。
加密过程是针对明文文件进行加密,采用读取字符的方法,对每一个字符通过映射的方法进行加密,完成加密后写人加密文件。在本节的示例中所包含的字符由26个小写字母和空格组成的,因过程比较简单,单表代替密码算法的实现直接采用函数的方法来实现,具体Cpp源码如下:
加密过程是针对明文文件进行加密,采用读取字符的方法,对每一个字符通过映射的方法进行加密,完成加密后写人加密文件。在本节的示例中所包含的字符由26个小写字母和空格组成的,因过程比较简单,单表代替密码算法的实现直接采用函数的方法来实现,具体Cpp源码如下:
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
const char c[27]={'d','j','k','z','u','x','c','m','l','i','w','b','v','n','o','p','q','a','r','s','g','h','f','t','y','e',' '};
void encryption(ifstream& fin, ofstream& fout);
void decryption(ifstream& fin, ofstream& fout);
int main(){
// 加密
ifstream fin;
ofstream fout ;
fin.open("file1_1.in");
if(fin.fail())
{
cout<<"File open error!(Input)"<< endl;
exit (1) ;
}
fout.open("file1_1.out");
if(fout.fail()){
cout<<"File open error!(Outpot)"<< endl;
}
encryption(fin, fout);
fin.close();
fout.close();
// 解密
ifstream fin_de;
ofstream fout_de;
fin_de.open("file1_1.out");
if(fin_de.fail())
{
cout<<"File open error!(Input)"<< endl;
exit (1) ;
}
fout_de.open("file1_1_de.out");
if(fout_de.fail()){
cout<<"File open error!(Outpot)"<< endl;
}
decryption(fin_de, fout_de);
fin_de.close();
fout_de.close();
return 0;
}
void encryption(ifstream& fin, ofstream& fout){
char next;
char ch;
int i;
while(fin.get(next)){
if(next>='a' && next<='z'){
i=next-'a';
ch=c[i];
fout<<ch;
}
else{
fout<<' ';
}
}
}
void decryption(ifstream& fin, ofstream& fout){
char ch;
char chout;
while(fin.get(ch)){
for(int i=0; i<=26; i++){
if(ch==c[i]){
if(i==26){
fout<<' ';
}else{
chout=char('a'+i);
fout<<chout;
}
}
}
}
}
加密的效果图:file1_1.in是输入,file1_1.out是输出。
解密的效果图:file1_1.out是输入,file1_1_de.out是输出。
- 26个字母与空格的单表替换是通过const char c[27]来完成的,具体的明文与密文之间字符的映射关系根据具体情况来确定,读者在实践过程中可以自己定义明文与密文之间的映射关系。
- 替换函数void encryption(ifstream& fin, ofstream& fout) 的参数是文件输人流和文件输出流,输人和输出文件在主函数中定义。
- 在读取文件数据的时候采用的方法是fin.get(next),而不是fin>>next,当采用fin>>next来读取数据的时候,程序将会忽略明文文件中的空格。

