% function [ciphertext]=DES(plaintext,K0)
%DES加密主程序
%plaintext为明文的二进制串,ciphertext为加密后得到的十六进制密文
%=========================示例====================================
% 16进制到二进制的转换函数
plaintext=['0' '1' '2' '3' '4' '5' '6' '7' '8' '9' 'A' 'B' 'C' 'D' 'E' 'F'];
K0=['0' '1' '2' '3' '4' '5' '6' '7' '8' '9' 'A' 'B' 'C' 'D' 'E' 'F'];
for i=1:length(plaintext)
plaintext_dec(i)=hex2dec(plaintext(i));
plaintext_bin(4*i-3:4*i)=dec2bin(plaintext_dec(i),4);
K0_dec(i)=hex2dec(K0(i));
K0_bin(4*i-3:4*i)=dec2bin(K0_dec(i),4);
end
K0=[0 0 0 0 0 0 0 1 0 0 1 0 0 0 1 1 0 1 0 0 0 1 0 1 0 1 1 0 0 1 1 1 1 0 0 0 1 0 0 1 1 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 1 0 1 1 1 1];
plaintext=K0;
%=================================================================
%IP,IP_1置换矩阵
IP0=[58 50 12 34 26 18 10 2 60 52 44 36 28 20 12 4
62 54 46 38 30 22 14 6 64 56 48 40 32 24 16 8
57 49 41 33 25 17 9 1 59 51 43 35 27 19 11 3
61 53 45 37 29 21 13 5 63 55 47 39 31 23 15 7];
IP_10=[40 8 48 16 56 24 64 32 39 7 47 15 55 23 63 31
38 6 46 14 54 22 62 30 37 5 45 13 53 21 61 29
36 4 44 12 52 20 60 28 35 3 43 11 51 19 59 27
34 2 42 10 50 18 58 26 33 1 41 9 49 17 57 25];
%将初始输入矩阵变成向量,方便运算
IP=reshape(IP0',1,64);IP_1=reshape(IP_10',1,64);
%调用函数,求出16个子密钥
[K]=create_key(K0);
%明文初始置换IP
for i=1:64
L(i)=plaintext(IP(i));
end
%记录L0,R0
LR(:,:,1)=reshape(L',2,32);
%16圈DES加密
for i=1:16
LR(1,:,i+1)=LR(2,:,i);
T=fun(LR(2,:,i),K(i,:));
LR(2,:,i+1)=xor(LR(1,:,i),T);
end
final=[LR(2,:,17) LR(1,:,17)];
%逆初始置换IP_1
for j=1:64
ciphertext0(j)=final(IP_1(j));
end
%将二进制串还原成16进制
for k=1:16
temp(k)=ciphertext0(4*k-3)*8+ciphertext0(4*k-2)*4+ciphertext0(4*k-1)*2+ciphertext0(4*k);
ciphertext(k)=dec2hex(temp(k));
end
%==============================结束==========================================
评论1