%clear all
%close all
%clc



%%%%%%%%%%%%%%%% Input data%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[filename, pathname] = uigetfile( {'*.bmp';}, 'Pick a file');
name=[ pathname filename];
data=imread(name);
%data=imresize(data,[64 64])

h=2;% number of bytes in a block (Tb=h*8)
r=4;% number of rounds
sk=16 % number of byes in a block cipher
strh='SHA-512';
%  mode=0==> ECB, 
%  mode 1==> CBC

mode=1



% calculate the length of data
SI=size(data);
%len=SI(1)*SI(2)*SI(3);
%lenBits=len*8;
%data_line=reshape(double(data),1,len); 

figure()
imshow(uint8(data));

%%%%%%%%%%%%%%%%% Key generation%%%%%%%%%%%%%%%%%%%%%%%%
Secretkey=floor(rand(1,sk)*256);
counter=floor(rand(1,sk)*256);
%%%%%%%%%%%%%%%%%%%%%%%%%Creation of cipher layer's%%%%%%%%%%%%%%%%%%%%
[RK,Sbox,Pbox]=Dynamickeygenerationnew(Secretkey,counter,strh,h);
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%% Change in data block%%%%%%%%%%%%%%%%%%%%%%%% 




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Encryption Process%%%%%%%%%%%%%%%%%%%%%
tic
if mode==0
eimg =encryptionprocess2(data,h,RK,Sbox,Pbox,r);
elseif mode==1
IV=double(floor(rand(1,h)*256));  
eimg =encryptionprocess2_CBC(data,h,RK,Sbox,Pbox,r,IV);       
end

toc
eimg2=reshape(eimg,size(data));

figure()
imshow(uint8(eimg2));

%%%%%%%%%%%%%%%%%%%%% Decryption Side%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%% calculate the inverse substitution and diffusion
%%%%%%%%%%%%%%%%%%%% layer%%%%%%%%%%%%%%%%
 Inv_Sbox= inverse_tables(Sbox);
 Inv_Pbox= inverse_tables2(Pbox);
 
 
 if mode==0
 dimg =decryptionprocess2(eimg,h,RK,Inv_Sbox,Inv_Pbox,r);
elseif mode==1

 dimg =decryptionprocess2_CBC(eimg,h,RK,Inv_Sbox,Inv_Pbox,r,IV);      
 end

%  tic
%  dimg =decryptionprocess2(eimg,h,RK,Inv_Sbox,Inv_Pbox,r);
%  toc
 dimg=reshape(dimg,size(data));
 figure()
 imshow(uint8(dimg));
 
