来自信息安全的作业,包含两个文件,读者需要自己创建.只进行了两轮des加密,输入为字符
输出为8位的数字
密文是“ABCD”
输出结果:
代码
% 实现3-des 算法 % 2019-5-15 % clear all; text='ABCD'; % ascii码65 66 67 68 P10=[3 5 2 7 4 10 1 9 8 6]; P8=[6 3 7 4 8 5 10 9]; P4=[2 4 3 1]; K=[1 0 1 0 0 0 0 0 1 0]; IP=[2 6 3 1 4 8 5 7]; IP_len=length(IP); IPinv=[4 1 3 5 7 2 8 6]; EP=[4 1 2 3 2 3 4 1]; S0=[1 0 3 2;3 2 1 0;0 2 1 3;3 1 0 2]; S1=[0 1 2 3;2 0 1 3;3 2 1 0;2 1 0 3]; % S0ch=['01001110';'11100100';'00100111';'11010010']; % S1ch=['00011011';'10000111';'11100100';'10010011']; %% 先获得密钥K1与K2 matrixP10=K(P10); lenP10=length(matrixP10); matrixP10_L=matrixP10(1:lenP10/2); matrixP10_Llen=length(matrixP10_L); % 左移一位 matrixP10_L=matrixP10_L([2:matrixP10_Llen,1]); matrixP10_R=matrixP10(lenP10/2+1:lenP10); matrixP10_Rlen=length(matrixP10_R); % 右移一位 matrixP10_R=matrixP10_R([2:matrixP10_Rlen,1]); K1temp=[matrixP10_L,matrixP10_R]; K1=K1temp(P8); % 左右进行移两位 matrixP10_L=matrixP10_L([3:matrixP10_Llen,1:2]); matrixP10_R=matrixP10_R([3:matrixP10_Rlen,1:2]); K2temp=[matrixP10_L,matrixP10_R]; K2=K2temp(P8); %% 进行F函数的实现 dec2bin() 实现数据到二进制的转换 text_len=length(text); text_matrix=zeros(text_len,8); % text_matrix记录文本转换矩阵 standN=8; for i=1:text_len % 将文本转化为八位的二进制 temp=dec2bin(text(i)); temp_len=length(temp); for j=1:standN-temp_len temp=['0',temp]; end tempbin=changebin(temp); text_matrix(i,:)=tempbin; end % 进行两轮循环 count=2; P4bin=zeros(1,4); % 存储二进制的P4矩阵 mainK=[K1;K2]; coding=zeros(size(text_matrix));% 初始化加密文本 N=1; for i=1:text_len temprow=text_matrix(i,:); temp=temprow(IP); for N=1:count IP_L=temp(1:IP_len/2); IP_R=temp(IP_len/2+1:IP_len); tempIP_R1=IP_R(EP(1:4)); tempIP_R2=IP_R(EP(5:8)); EP8=[tempIP_R1,tempIP_R2]; % 完成EP8矩阵的扩展 result1=xor(EP8,mainK(N,:)); S0L=result1(1:4); S1R=result1(5:8); S0output=S0(2*S0L(1)+S0L(4)+1,2*S0L(2)+S0L(3)+1); S1output=S1(2*S1R(1)+S1R(4)+1,2*S1R(2)+S1R(3)+1); P4input=[S0output,S1output]; % 完成S矩阵数字到二进制的转换 P4bin(1)=floor(P4input(1)/2); P4bin(2)=mod(P4input(1),2); P4bin(3)=floor(P4input(2)/2); P4bin(4)=mod(P4input(2),2); P4output=P4bin(P4); SWinput=xor(IP_L,P4output); if N==1 % 完成SW模块 temp=[IP_R,SWinput]; end end tempcoding=[SWinput,IP_R]; coding(i,:)=tempcoding(IPinv); end disp(coding);
% 第二个函数
% 该函数主要是将字符串的 ‘0101‘编程数字0 1 0 1 % 2019-5-15 function temp=changebin(str) strlen=length(str); temp=zeros(1,strlen); for i=1:strlen if str(i)=='0' temp(i)=0; elseif str(i)=='1' temp(i)=1; end end