凯撒密码加解密及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,……那么有如下公式,(这里的模运算的结果均为正):
可以稍加推广,用字母表后的第key个字母代替,则有:
甚至,字母表也可以是任意的,不妨设字母表为,对应的数字为0~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++实现的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03如何安装 App 并连接到飞牛 NAS?-icode9专业技术文章分享
- 2024-10-03如何安装飞牛 TV 并连接到影视服务器?-icode9专业技术文章分享
- 2024-10-03如何在PVE和ESXI上安装飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS安装系统异常情况处理-icode9专业技术文章分享
- 2024-10-03飞牛NAS如何创建存储空间?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS硬盘会自动休眠吗?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何安装飞牛影视和创建媒体库?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何为家人朋友开通影视账号?-icode9专业技术文章分享