MATLAB实现滚动密钥密码
生活随笔
收集整理的這篇文章主要介紹了
MATLAB实现滚动密钥密码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
滾動密鑰密碼
對于周期代換密碼,當密鑰的長度d和明文一樣長時,就成為滾動密鑰密碼。
具體可見如下表所示:
| 密鑰 | beijingmeetatnineinthe |
| 密文 | NIMCIGTURIBNMUMRZMABUK |
MATLAB代碼如下:
function keyT = getKey(key,plaintext) %getKey:滾動密碼的密鑰生成函數 %key:密鑰 %plaintext:明文 %keyT:密鑰對照表p_long = length(plaintext); key=upper(key); for i=1:p_longkeyT(1,i)=plaintext(i);if i<=length(key)keyT(2,i)=key(i);endif i>length(key)keyT(2,i)=plaintext(i-length(key));end end end function ciphertext = encryption(keyT,plaintext) %encryption:滾動密碼的加密算法 %keyT:密鑰 %plaintext:明文 %ciphertext:密文ciphertext = ''; p_long=length(plaintext); for i=1:p_longif abs(plaintext(i))<=65+26&&abs(plaintext(i))>=65temp=mod(abs(keyT(2,i))+abs(plaintext(i))-65-65,26);ciphertext=strcat(ciphertext,char(temp+97));endif abs(plaintext(i))>=97&&abs(plaintext(i))<=97+26temp=mod(abs(keyT(2,i))+abs(plaintext(i))-97-65,26);ciphertext=strcat(ciphertext,char(temp+65));end end end function plaintext = decrypt(keyT,ciphertext) %decrypt:解密算法 %ciphertext:密文 %plaintext:明文 %keyT:密鑰c_long = length(ciphertext); plaintext=''; for i=1:c_longif abs(ciphertext(i))<=65+26&&abs(ciphertext(i))>=65temp=mod(-abs(keyT(2,i))+abs(ciphertext(i))-65-65+26,26);plaintext=strcat(plaintext,char(temp+97));endif abs(ciphertext(i))>=97&&abs(ciphertext(i))<=97+26temp=mod(-abs(keyT(2,i))+abs(ciphertext(i))-97-65+26,26);plaintext=strcat(plaintext,char(temp+65));end end end測試代碼如下:
disp('密匙短語如下:');key='abcd';disp(key);disp('明文如下:');plaintext='csdghfnjsdfgYBGUGY';disp(plaintext);keyT = getKey(key,plaintext); ciphertext = encryption(keyT,plaintext);disp('密文如下:');disp(ciphertext); plaintext = decrypt(keyT,ciphertext);disp('解密后明文如下:');disp(plaintext);測試結果如下:
>> ceshi 密匙短語如下: abcd 明文如下: csdghfnjsdfgYBGUGY 密文如下: CTFJPDWVFOYVwkrgez 解密后明文如下: csdghfnjsdfgYBGUGY密鑰如下:
'csdghfnjsdfgYBGUGY''ABCDcsdghfnjsdfgYB'總結
以上是生活随笔為你收集整理的MATLAB实现滚动密钥密码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 回溯——伯努利装错信封问题
- 下一篇: leetcode -39组合总数