MATLAB实现滚动密钥密码

滚动密钥密码

对于周期代换密码,当密钥的长度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'
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值