单表代换密码体制
一、單表代換密碼體制
所謂代換,是指將明文的字符,用字符集的其他字符代替,從而變成密文。單表代換,顧名思義,有一張代換表,表中描述了代換關系。值得注意的是,代換關系可以是一對多,但是必須要保證的可逆性,即一個密文字符唯一對應于一個明文的字符,也就是密文解密的唯一性,一個密文解密出一個明文。不過,一個明文可以加密成多個密文。下面舉一個例子。
假設字符集為{a,b,c},,代換所用的字符集為{1,2,3,4,5,6}。
代換表如下:
| 密文字符 | 1,2 | 3,4 | 5,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; }總結
- 上一篇: 张量Tensor@最强分析
- 下一篇: 【0304】密码分类