单表代换密码体制

一、单表代换密码体制

所谓代换,是指将明文的字符,用字符集的其他字符代替,从而变成密文。单表代换,顾名思义,有一张代换表,表中描述了代换关系。值得注意的是,代换关系可以是一对多,但是必须要保证的可逆性,即一个密文字符唯一对应于一个明文的字符,也就是密文解密的唯一性,一个密文解密出一个明文。不过,一个明文可以加密成多个密文。下面举一个例子。
假设字符集为{a,b,c},,代换所用的字符集为{1,2,3,4,5,6}。
代换表如下:

明文字符abc
密文字符1,23,45,6

则明文ab可以加密成13,14,23,或24这四种密文中的一种。反之,密文13只能解密成ab。
这是代换的一般形式。
当然,我们通常采用的更加特殊的代换,也就是明文字符集和密文字符集一样,这样加解密的过程就是一一对应。每一张代换表就是一个密钥,不一定满足某种规律,他只是对应于字符集的一种排列。所以,一个有n个字符的字符集,最多有n!种不同的代换表,也就是密钥空间为n!。

二、英文字母单表代换

现在给出一个26个小写英文字母的单表代换例子。

#include<iostream>
#include<map>
using namespace std;
//encrypt, message is clear text and table is the substitution table.
string encrypt(string message,map<char,char>& table){
	for(int i=0;i<message.size();i++){
		message[i]=table[message[i]];
	}
	return message;
}
//decipher, rtable is the inverse of substitution table
string decipher(string ciphertext,map<char,char>& rtable){
	for(int i=0;i<ciphertext.size();i++){
		ciphertext[i]=rtable[ciphertext[i]];
	}
	return ciphertext;
}
int main(){
	map<char,char> table,rtable;
	table['a']='n',table['b']='d',table['c']='q',table['d']='g',table['e']='i';
	table['f']='a',table['g']='m',table['h']='z',table['i']='s',table['j']='w';
	table['k']='y',table['l']='t',table['m']='c',table['n']='l',table['o']='f';
	table['p']='r',table['q']='e',table['r']='p',table['s']='k',table['t']='u';
	table['u']='o',table['v']='x',table['w']='v',table['x']='j',table['y']='h',table['z']='b';
	for(auto it:table){
		rtable[it.second]=it.first;
	}
	cout<<"Please input message:";
	string message;
	cin>>message;
	cout<<"The ciphertext is:";
	string ciphertext;
	ciphertext=encrypt(message,table);
	cout<<ciphertext<<endl;;
	cout<<"After deciphering:"<<decipher(ciphertext,rtable)<<endl;
}
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值