移位密码原理及算法实现

本文介绍了移位密码的基本原理及其实现方法,包括其加密和解密过程,并通过C++代码示例展示了如何使用移位密码对文本进行加密和解密。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

移位密码算法原理

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

  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

 

转载于:https://www.cnblogs.com/ECJTUACM-873284962/p/7872567.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值