凯撒密码加解密及c++实现

一、原理

凯撒密码是已知最早的代替密码(代替密码:用字母表的其他字母代替 明文字母,形成密文)。凯撒密码使用的字母表是26个英文字母,明文字母用其后的第三个字母代替。

一般,用小写字母代表明文(message),大写字母代表密文(ciphertext)。明文:abcd,则对应密文:DEFG。应该注意的是,字母表是循环的,也就是z的下一个字母是a,而z对应的密文是C。

现在,我们不妨把字母映射为0~25的数字,即a对应0,b对应1,c对应2,……那么有如下公式,(这里的模运算的结果均为正):

ciphertext=(message+3) mod 26

message=(ciphertext-3) mod 26

可以稍加推广,用字母表后的第key个字母代替,则有:

ciphertext=(message+key) mod 26

message=(ciphertext-key)mod 26

甚至,字母表也可以是任意的,不妨设字母表为a_{0},a_{1},a_{2},...,a_{n},对应的数字为0~n,则:

ciphertext=(message+key)mod (n)

message=(ciphertext-key)mod(n)


二、c++代码实现

#include<iostream>
#include<vector>
using namespace std;
//encoding function
string encode(string message,int key,vector<char>& set){
	int index;
	for(int i=0;i<message.size();i++){
		for(int j=0;j<set.size();j++){
			if(message[i]==set[j]){
				index=(j+key)%set.size();
				message[i]=set[index];
				break;
			}
		}
	}
	return message;
}
//decoding function
string decode(string ciphertext,int key,vector<char>& set){
	key=set.size()-key;
	return encode(ciphertext,key,set);
}
int main(){
	//The characters set, which you can change as you like 
	vector<char> set={'a','b','c','d','e','f','g','h','i','j','k','l','m',
					'n','o','p','q','r','s','t','u','v','w','x','y','z'};
	int key=3;
	cout<<"Please input the message:";
	string message;
	cin>>message;
	string ciphertext;
	ciphertext=encode(message,key,set);
	cout<<"The ciphertext is:"<<ciphertext<<endl;
	cout<<"After decoding:"<<decode(ciphertext,key,set)<<endl;
}

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值