滚动密钥密码
对于周期代换密码,当密钥的长度d和明文一样长时,就成为滚动密钥密码。
具体可见如下表所示:
明文 | meetatnineintheevening |
---|---|
密钥 | beijingmeetatnineinthe |
密文 | NIMCIGTURIBNMUMRZMABUK |
MATLAB代码如下:
function keyT = getKey(key,plaintext)
%getKey:滚动密码的密钥生成函数
%key:密钥
%plaintext:明文
%keyT:密钥对照表
p_long = length(plaintext);
key=upper(key);
for i=1:p_long
keyT(1,i)=plaintext(i);
if i<=length(key)
keyT(2,i)=key(i);
end
if 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_long
if abs(plaintext(i))<=65+26&&abs(plaintext(i))>=65
temp=mod(abs(keyT(2,i))+abs(plaintext(i))-65-65,26);
ciphertext=strcat(ciphertext,char(temp+97));
end
if abs(plaintext(i))>=97&&abs(plaintext(i))<=97+26
temp=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_long
if abs(ciphertext(i))<=65+26&&abs(ciphertext(i))>=65
temp=mod(-abs(keyT(2,i))+abs(ciphertext(i))-65-65+26,26);
plaintext=strcat(plaintext,char(temp+97));
end
if abs(ciphertext(i))>=97&&abs(ciphertext(i))<=97+26
temp=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'