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

2021/7/26 22:06:43

本文主要是介绍凯撒密码加解密及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;
}



这篇关于凯撒密码加解密及c++实现的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程