移位密码原理及算法实现

 

移位密码算法原理

  移位密码又称为移位代换密码,是单表代换密码中的一种,它的加解密过程可以用以下方式表示:

  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

 

posted @   Angel_Kitty  阅读(6316)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示
西雅图
14:14发布
西雅图
14:14发布
6°
西南风
5级
空气质量
相对湿度
93%
今天
中雨
3°/9°
周日
雨夹雪
3°/6°
周一
小雨
3°/10°