移位密码又称为移位代换密码,是单表代换密码中的一种,它的加解密过程可以用以下方式表示:
C=Ek(s)=(s+k) mod n,
S=Dk(c)=(c-k) mod n,
其中,c表示密文字符,s表示明文字符,k表示移位的数字,n表示代换字符集的字符总个数,当字符集为26个字母时的移位算法就是凯撒密码。
1 #include <iostream>
2 #include <fstream>
3 #include <cstdlib>
4 using namespace std;
5 class Shift
6 {
7 public:
8 Shift();
9 static void encryption(ifstream& fin,ofstream& fout,int n);
10 static void decryption(ifstream& fin,ofstream& fout,int n);
11 };
12 void Shift::encryption(ifstream& fin,ofstream& fout,int n)//加密过程
13 {
14 char next;
15 while(fin.get(next))
16 {
17 fout<<char((int(next)+n)%128);
18 }
19 }
20 void Shift::decryption(ifstream& fin,ofstream& fout,int n)//解密过程
21 {
22 char next;
23 while(fin.get(next))
24 {
25 fout<<char((int(next)-n)%128);
26 }
27 }
28 int main()
29 {
30 ifstream fin;
31 ofstream fout;
32 fin.open("file1_2.in");
33 while(fin.fail())
34 {
35 cout<<"File open error!(Input)"<<endl;
36 exit(1);
37 }
38 fout.open("file1_2.out");
39 if(fout.fail())
40 {
41 cout<<"File open error!(Output)"<<endl;
42 }
43 Shift::encryption(fin,fout,1);
44 fin.close();
45 fout.close();
46 return 0;
47 }
输入file1_2.in
//file1_2.in
we will attack tomorrow morning
输出file1_2.out
//file1_2.out
xf!xjmm!buubdl!upnpsspx!npsojoh