Secure voice transmission using DES

PROJECT VIDEO

ABSTRACT

Voice over Internet protocol has become a popular alternative to public switched telephone network. The flexibility and cost efficiency are the key factors luring enterprises to transition to VoIP. As VoIP technology matures and become increasingly popular so it also gains the attention of the attacker who attacks on the VoIP conversation and wishes to eardrop the conversation. In this paper we first describe the phrase spotting technique used to eavesdrop the conversation and defence approach for eavesdropping attack.

INTRODUCTION

Voice over Internet Protocol is a communication protocol and technology that allow user to make phone calls, video conferencing etc using a broadband internet connection instead of analog phone line. Firstly voice signal separated into frames which are stored into data packets and then transported over IP network using communication protocol. VoIP technology has recently become an important part of part of our day to day life; millions of people speak over internet but few of them understand the security issues related to voice communication. While people are not aware of the fact that someone could listen to their VoIP calls. An eavesdropper can detect that specific phrases were used in discussion without ever hearing the actual speech of the user. Phrase spotting Technique used to eavesdrop on VoIP conversation.  Phrase spotting technique is harmful to privacy. [1] To make system complete, it would also be rational to implement an encryption scheme based on public key cryptography to transfer the information about the padding length securely.

Cryptography Goals:

  • Confidential: The protection of data from unauthorized party and transmitted information is accessible only for reading by authorized parties.
  • Authentication: the authentication service is concerned with assuring that a communication is authentic and the assurance that the communicating entity is the one that is claims to be.
  • Integrity: assurance that the data received are exactly sent by an authorized entity. Only authorize parties are able to modify and stored information.
  • Non repudiation: It prevents either sender or receiver from denying a transmitted message.
  • Access Control: It is the ability to limit or control the access to host system and application via communication link.
  • Availability: Computer system assets are available to authorized parties when need

PROPOSED DEFENSE APPROACH FOR EAVESDROPPING 

In this section we present the defence approach for eavesdropping attack. It minimizes the chance of attack on VoIP calls. It would also be rational to implement an encryption scheme based on public key cryptography to transfer the information about the padding length securely [1]. A protection technique in which, padding each packet to different value. So that an attacker would not be able to differentiate between low bit rate and high bit rate. Conversation divides into two parts one side is sender and another side is receiver side. At the sender side firstly sender read an audio file, find out the indexes with low bit rate. For securing the conversation, pad the indexes with low bit rate. We are using 10% value of highest bit rate. Add the random noise at threshold indexes with maximum amplitude of highest bit rate. Then apply Data Encryption Standard [5] to all indexes, for encryption and decryption. Then it encrypts the noisy signal and indexes where noise is added. It is symmetric key where both parties share the same key for en- and decryption. At the receiver side, it decodes the noisy signal and removes the noises from the signal. Then get the original audio file. This technique minimizes the attack.

Transmitter

  • Read an audio file.
  • Then find out the indexes with low bit rate using a threshold schema.
  • For simplicity, we are using 10% value of the highest bit rate.
  • Then save the indexes of the signal where thresholding is done.
  • Insert the random noise at threshold indexes with maximum amplitude of highest bit rate.
  • This is the constant bit rate signal which is to be transfer. Let this signal be A
  • And then apply Data Encryption Standard (DES) to all the indexes which were thresholded. Let this signal be B
  • Then we get two signals that is A and B. These signals will be transfer through the channel.

Receiver

  • Receiver gets two signals. One is DES signal (B) and second is noisy signal (A).
  • Decode the DES signal using appropriate key
  • The decoded information are the indexes where the random noise is to be remove from the noisy signal
  • Remove the noises from the noises signal.
  • Then obtain the final audio at the receiver side

MATLAB SOURCE CODE

Instructions to run the code

  1. Copy each of below codes in different M files.
  2. Place all the files in same folder
  3. Use files from below link and place in the same folder
    1. def
    2. mike
    3. position
    4. reconstructed_audio
  4. Also note that these codes are not in a particular order. Copy them all and then run the program.
  5. Run the “final.m” file

Code 1 – Script M File – final.m

clear all
close all
clc
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read the audio file=65535 bits
disp('Read the audio file')
% maximum length
[W,Fs,nbits]=read_audio;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% calculate the threshold value
disp('Calculate the threshold value')
thresh=cal_thresh(W);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% values in between threshold limits
T=find(W<=thresh & W>=-thresh);
% plot(W)
% hold on
% plot(W(T),'r')
% pause
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% making changes to the input audio
disp('Making changes to the input audio')
Wnew=changed_audio(W,T);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% plotting new audio and original audio
disp('Plotting new audio and original audio')
figure
subplot(2,1,1)
plot(W)
%axis([0 length(W) min(W)-0.2 max(W)+0.2])
title('Original audio')
subplot(2,1,2)
plot(Wnew)
%axis([0 length(W) min(W)-0.2 max(W)+0.2])
title('Changed audio')
wavwrite(Wnew,Fs,nbits,'reconstructed_audio.wav')
% ENCRYPTION PART %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp('Encryption part')
[Edata,KEY]=encryption(T);
% DECRYPTION PART %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp('Decryption part')
[Tnew,Tnew2]=decryption(Edata,KEY);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Wout=Wnew;
Tnew2=Tnew2(1:length(T));
Wout(Tnew2)=thresh;
Wout=Wout(1:length(W));

% figure
% subplot(3,1,1)
figure, plot(W)
title('Original audio')
% subplot(3,1,2)
figure, plot(Wnew)
title('Audio with constant bit rate')
% subplot(3,1,3)
figure, plot(Wout)
title('Recovered audio')
% plot(T)
% hold on
% plot(Tnew,'r')
% plot(Tnew2,'g')
% 
[PSNR,MSE,MAXERR,L2RAT] = measerr(W,Wout);
disp(MSE)
wavwrite(Wout,Fs,nbits,'reconstructed_audio.wav')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Code 2 – Function M File – encryption.m

function [Edata,KEY]=encryption(T)

n=0;
l=mod(length(T),4);
for i=1:4:(length(T)-l)
    plaintext=[fliplr(dec2binvec(T(i),16)) fliplr(dec2binvec(T(i+1),16)) fliplr(dec2binvec(T(i+2),16)) fliplr(dec2binvec(T(i+3),16))];
    [ciphertext,key]=DES(plaintext,'ENC');
    n=n+1;
    Edata(n,:)=ciphertext;
    KEY(n,:)=key;
%     pause
end

if l~=0
    if l==1
        plaintext=[fliplr(dec2bin(T(end),16)) zeros(1,48)];
    elseif l==2
        plaintext=[fliplr(dec2bin(T(end-1),16)) fliplr(dec2bin(T(end),16)) zeros(1,32)];
    elseif l==3
        plaintext=[fliplr(dec2bin(T(end-2),16)) fliplr(dec2bin(T(end-1),16)) fliplr(dec2bin(T(end),16)) zeros(1,16)];
    end
    [ciphertext,key]=DES(plaintext,'ENC');
    Edata(n+1,:)=ciphertext;
    KEY(n+1,:)=key;
end

end

Code 3 – Function M File – DES.m

function [varargout] = DES(input64,mode,key)
%DES: Data Encryption Standard
% Encrypt/Decrypt a 64-bit message using a 64-bit key using the Feistel
% Network
% -------------------------------------------------------------------------
% Inputs: 
%        input64 = a 64-bit message 
%           mode = either 'ENC' encryption or 'DEC' decryption (default 'ENC')
%            key = a 56/64-bit key (optional under 'ENC', but mandatory under 'DEC')
% Outputs:
%   varargout{1} = output64, a 64-bit message after encryption/decryption
%   varargout{2} = a 64-bit key, if a 64-bit key is not provided as an input
% -------------------------------------------------------------------------
% Demos:
%    plaintext = round(rand(1,64));
%    [ciphertext,key] = DES(plaintext);       % Encryption syntex 1
%   [ciphertext1,key] = DES(plaintext,'ENC'); % Encryption syntex 2
%   deciphertext1 = DES(ciphertext1,'DEC',key);% Decryption syntex
% 
%   key56 = round(rand(1,56));
%   [ciphertext2,key64] = DES(plaintext,'ENC',key56);% Encryption syntex 3 (56-bit key)
%   deciphertext2 = DES(ciphertext2,'DEC',key64);     % Decryption syntex   (64-bit key)
%   ciphertext3 = DES(plaintext,'ENC',key64);       % Encryption syntex 3 (64-bit key)
%   deciphertext3 = DES(ciphertext3,'DEC',key56);     % Decryption syntex   (56-bit key)
%   
%   % plot results
%    subplot(4,2,1),plot(plaintext),ylim([-.5,1.5]),xlim([1,64]),title('plaintext')
%    subplot(4,2,2),plot(ciphertext),ylim([-.5,1.5]),xlim([1,64]),title('ciphertext')
%   subplot(4,2,3),plot(deciphertext1),ylim([-.5,1.5]),xlim([1,64]),title('deciphertext1')
%   subplot(4,2,4),plot(ciphertext1),ylim([-.5,1.5]),xlim([1,64]),title('ciphertext1')
%   subplot(4,2,5),plot(deciphertext2),ylim([-.5,1.5]),xlim([1,64]),title('deciphertext2')
%   subplot(4,2,6),plot(ciphertext2),ylim([-.5,1.5]),xlim([1,64]),title('ciphertext2')
%   subplot(4,2,7),plot(deciphertext3),ylim([-.5,1.5]),xlim([1,64]),title('deciphertext3')
%   subplot(4,2,8),plot(ciphertext3),ylim([-.5,1.5]),xlim([1,64]),title('ciphertext3')
% -------------------------------------------------------------------------
% NOTE: 
%    If a 64-bit key is provided, then its bit parities will be checked. If
%    a 56-bit key is provided, then it is automatically added 8 partity
%    checking bits. However, the 8 parity bits are never used in
%    DES encryption/decryption process. They are included just for the 
%    completeness of a DES implementation. 
% -------------------------------------------------------------------------
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                              Functions                                 %%
% 1-keyParityCheck(k)----------------to check the parity of the key
% 2-HALF_L(message)------------------left half of the message
% 3-HALF_R(message)------------------right half of the message
% 4-EF = @(halfMessage)--------------32 bit to 48 bit
% 5-KM = @(expandedHalfMessage,rK)---xor operation on 48 bit rK and 48 bit expandedHalfMessage
% 6-PBOX = @(halfMessage)------------32 bit half message permuted to a 32 bit message
% 7-IP = @(message)------------------initial permutation of 64 bits input
% 8-FP = @(message)------------------final permutation of 64 bits output
% 9-PC1L = @(key64)------------------permutation of left half key (28 bit)
% 10-PC1R = @(key64)-----------------permutation of right half key (28 bit)
% 11-PC2 = @(key56)------------------second permutation of the 56 bit permuted key before the key mixing operation
% 12-KS = @(key28,s)-----------------key shift function

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                           0. Initialization                           %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 0.1 check input
error(nargchk(1,3,nargin)); % gives error if number of input is less then 1(minargs) and more then 3(maxargs). nargin is the no. of inputs.
switch nargin
    case 1
        mode = 'ENC'; % checking the second input parameter (encryption or decryption)
        K = round(rand(8,7)); % providing a key since no key was entered, this will give only binary values
        K(:,8) = mod(sum(K,2),2); % note these eight bits of key are never used in encryption % 8th row provided for parity
        K = reshape(K',1,64); % making the above matrix K(8x8) into K(1,64)
        varargout{2} = K; % provides key if no key given
    case 2
        switch mode
            case 'ENC' % checking the second input parameter (encryption or decryption)
                K = round(rand(8,7));% providing a key since no key was entered, this will give only binary values
                K(:,8) = mod(sum(K,2),2); % note these eight bits of key are never used in encryption
                K = reshape(K',1,64); % making the above matrix K(8x8) into K(1,64)
                varargout{2} = K;% provides key if no key given
            case 'DEC' % checking the second input parameter (encryption or decryption)
                error('Key has to be provided in decryption mode (DEC)')
            otherwise % no mode defined
                error('WRONG working mode!!! Select either encrtyption mode: ENC or decryption mode: DEC !!!')
        end
    case 3 
        if isempty(setdiff(unique(key),[0,1])) % check provided key type % key only has binary values
            if numel(key) == 64  % check provided key parity %chk the length of key
                keyParityCheck = @(k) (sum(mod(sum(reshape(k,8,8)),2))==0); % function to check the parity of the key
                if keyParityCheck(key) == 1
                    K = key(:)';
                else
                    error('Key parity check FAILED!!!')
                end
            elseif numel(key) == 56 % add parity bits % 56 bits added, 8 bit parity will be added
                K = reshape(key,7,8)';% row vector key will be converted to 2D matrix of dim 7x8
                K(:,8) = mod(sum(K,2),2); % note these eight bits of key are never used in encryption %8th row added, K is now 8x8
                K = reshape(K',1,64);% 8x8 K is converted into 1x64 K
                varargout{2} = K; % 2nd output is given 
                display('Key parity bits added')
            else
                error('Key has to be either 56 or 64-bit long!!!')
            end
        else
            error('Key has to be binary!!!')
        end
end
        
% 0.2 check message length and type
if numel(input64)% == 64 && isempty(setdiff(unique(input64),[0,1])) % checking the input length, it has to be 64 bits
    P = input64;
else
    error('Message has to be a 64-bit message!!!')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                   1. Cryptographical primitives                       %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 1.1 define splitting function
HALF_L = @(message) message(1:32); % left half of message
HALF_R = @(message) message(33:64); % right half of message
% 1.2 define expansion function
EF = @(halfMessage) [halfMessage([32,4:4:28])',(reshape(halfMessage,4,8))',halfMessage([5:4:29,1])'];% 32 bit right half message converted into 48 bit message
% 1.3 define key mixing (KM)
KM = @(expandedHalfMessage,rK) xor(expandedHalfMessage,reshape(rK,6,8)');% xor operation btw 48 bit expanded msg and 48 bit key
% 1.4 define eight substitution tables
% input: 0	1   2   3   4   5   6   7   8   9   10  11  12  13  14  15
st{1} = [14	4	13	1	2	15	11	8	3	10	6	12	5	9	0	7;...
         0  15	7	4	14	2	13	1	10	6	12	11	9	5	3	8;...
         4	1	14	8	13	6	2	11	15	12	9	7	3	10	5	0;...
         15	12	8	2	4	9	1	7	5	11	3	14	10	0	6	13];
st{2} = [15	1	8	14	6	11	3	4	9	7	2	13	12	0	5	10;...
    	3	13	4	7	15	2	8	14	12	0	1	10	6	9	11	5;...
		0	14	7	11	10	4	13	1	5	8	12	6	9	3	2	15;...
		13	8	10	1	3	15	4	2	11	6	7	12	0	5	14	9];
st{3} = [10	0	9	14	6	3	15	5	1	13	12	7	11	4	2	8;...
		13	7	0	9	3	4	6	10	2	8	5	14	12	11	15	1;...
		13	6	4	9	8	15	3	0	11	1	2	12	5	10	14	7;...
		1	10	13	0	6	9	8	7	4	15	14	3	11	5	2	12];
st{4} = [7	13	14	3	0	6	9	10	1	2	8	5	11	12	4	15;...
		13	8	11	5	6	15	0	3	4	7	2	12	1	10	14	9;...
		10	6	9	0	12	11	7	13	15	1	3	14	5	2	8	4;...
		3	15	0	6	10	1	13	8	9	4	5	11	12	7	2	14];
st{5} = [2	12	4	1	7	10	11	6	8	5	3	15	13	0	14	9;...
		14	11	2	12	4	7	13	1	5	0	15	10	3	9	8	6;...
		4	2	1	11	10	13	7	8	15	9	12	5	6	3	0	14;...
		11	8	12	7	1	14	2	13	6	15	0	9	10	4	5	3];
st{6} = [12	1	10	15	9	2	6	8	0	13	3	4	14	7	5	11;...
		10	15	4	2	7	12	9	5	6	1	13	14	0	11	3	8;...
		9	14	15	5	2	8	12	3	7	0	4	10	1	13	11	6;...
		4	3	2	12	9	5	15	10	11	14	1	7	6	0	8	13];
st{7} = [4	11	2	14	15	0	8	13	3	12	9	7	5	10	6	1;...
		13	0	11	7	4	9	1	10	14	3	5	12	2	15	8	6;...
		1	4	11	13	12	3	7	14	10	15	6	8	0	5	9	2;...
		6	11	13	8	1	4	10	7	9	5	0	15	14	2	3	12];
st{8} = [13	2	8	4	6	15	11	1	10	9	3	14	5	0	12	7;...
		1	15	13	8	10	3	7	4	12	5	6	11	0	14	9	2;...
		7	11	4	1	9	12	14	2	0	6	10	13	15	3	5	8;...
		2	1	14	7	4	10	8	13	15	12	9	0	3	5	6	11];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the eight binary s-boxes 
for i = 1:8
    ST{i} = mat2cell(blkproc(st{i},[1,1],@(x) de2bi(x,4,'left-msb')),ones(1,4),ones(1,16)*4);
end
% 1.5 define subsitution function (SBOX)
SUBS = @(expandedHalfMessage,blkNo) ST{blkNo}{bi2de(expandedHalfMessage(blkNo,[1,6]),'left-msb')+1,bi2de(expandedHalfMessage(blkNo,[2:5]),'left-msb')+1};
SBOX = @(expandedHalfMessage) [SUBS(expandedHalfMessage,1);SUBS(expandedHalfMessage,2);...
                               SUBS(expandedHalfMessage,3);SUBS(expandedHalfMessage,4);...
                               SUBS(expandedHalfMessage,5);SUBS(expandedHalfMessage,6);...
                               SUBS(expandedHalfMessage,7);SUBS(expandedHalfMessage,8)];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 1.6 define permutation function (PBOX) % permute the 32 bit s box output into 32 bit p box output
PBOX = @(halfMessage) halfMessage([16  7 20 21  29 12 28 17 ... 
                                    1 15 23 26   5 18 31 10 ...
                                    2  8 24 14  32 27  3  9 ...
                                   19 13 30  6  22 11  4  25]);
% 1.7 define initial permutation (IP) % permutation od the 64 bit input message, one time operation
IP = @(message) message([58	50	42	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]);
% 1.8 define final permutation (FP) % final permutation of the output message, one time operation
FP = @(message) message([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]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                           2. key schedule                             %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 2.1 define permuted choice 1 (PC1) 
% keeping in mind not to include the parity bits i.e. every 8th bit is
% excluded in this operation.
PC1L = @(key64) key64([57	49	41	33	25	17	9 ...
                    1	58	50	42	34	26	18 ...
                    10	2	59	51	43	35	27 ...
                    19	11	3	60	52	44	36]);
PC1R = @(key64) key64([63	55	47	39	31	23	15 ...
                    7	62	54	46	38	30	22 ... 
                    14	6	61	53	45	37	29 ...
                    21	13	5	28	20	12	4]);
% 2.2 define permuted choice 2 (PC2)
PC2 = @(key56) key56([14 17	11	24	1	5	3	28 ...
                     15	6	21	10	23	19	12	4 ...
                     26	8	16	7	27	20	13	2 ...
                     41	52	31	37	47	55	30	40 ...
                     51	45	33	48	44	49	39	56 ...
                     34	53	46	42	50	36	29	32]);
% 2.3 define rotations in key-schedule (RK)
% round# 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6
   RK = [1 1 2 2 2 2 2 2 1 2 2 2 2 2 2 1];% amount of shifts in the 28 bit half keys before compressiona permutation
% 2.4 define key shift function (KS)
KS = @(key28,s) [key28(s+1:end),key28(1:s)]; % shifting the 28 bit key according to the iteration in "s"
% 2.5 define sub-keys for each round
leftHKey = PC1L(K); % 28-bit left half key, 1st permutation operation
rightHKey = PC1R(K);% 28-bit right half key, 1st permutation operation
for i = 1:16
    leftHKey = KS(leftHKey,RK(i)); % shifting the left half key (28 bit)
    rightHKey = KS(rightHKey,RK(i));% shifting the right half key (28 bit)
    key56 = [leftHKey ,rightHKey];% concatinating the shifted keys (56 bit)
    subKeys(i,:) = PC2(key56(:)); % 2nd permutation operation
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                           3. DES main loop                            %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 3.1 initial permutation
C = IP(P); % initial permutation of the 64 bit plaintext
switch mode
    case 'ENC' % if encryption, split 64 message to two halves
        L{1} = HALF_L(C); % left-half 32-bit
        R{1} = HALF_R(C); % right-half 32-bit
    case 'DEC' % if decryption, swapping two halves
        L{1} = HALF_R(C); % right-half 32-bit
        R{1} = HALF_L(C); % left-half 32-bit
end
% 3.2 cipher round 1 to 16
for i = 1:16
     L{i+1} = R{i}; % half key: 32-bit
     expended_R = EF(R{i}); % expended half key: 32-bit to 48-bit
     switch mode
        case 'ENC' % if encryption, apply sub-keys in the original order
            mixed_R = KM(expended_R,subKeys(i,:)); % mixed with sub-key: 48-bit
        case 'DEC' % if decryption, apply sub-keys in the reverse order
            mixed_R = KM(expended_R,subKeys(16-i+1,:)); % mixed with sub-key: 48-bit
     end
     substituted_R = SBOX(mixed_R); % substitution: 48-bit to 32-bit%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
     permuted_R = PBOX(reshape(substituted_R',1,32)); % permutation: 32-bit
     R{i+1} = xor(L{i},permuted_R); % Feistel function: 32-bit
end
% 3.3 final permutation
switch mode
    case 'ENC'
        C = [L{end},R{end}]; 
    case 'DEC'
        C = [R{end},L{end}];
end
output64 = FP(C);
varargout{1} = output64;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                   END                                 %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end

Code 4 – Function M File – decryption.m

function [Tnew,Tnew2]=decryption(Edata,KEY)

[r c]=size(Edata);
Tnew=[];
for j=1:r
    key=KEY(j,:);
    ciphertext=Edata(j,:);
    deciphertext=DES(ciphertext,'DEC',key);
    Tnew(j,:)=deciphertext;
%     pause
end

[r c]=size(Tnew);
Tnew2=[];
for i=1:r
%     Tnew(i,:)
    Tnew2=[Tnew2 bin2dec(num2str(Tnew(i,1:16))) bin2dec(num2str(Tnew(i,17:32))) bin2dec(num2str(Tnew(i,33:48))) bin2dec(num2str(Tnew(i,49:64)))];
%     pause
end

end

Code 5 – Function M File – Dec2Bin.m

function [txt_bin]=Dec2Bin(txt_dec)
%converting decimal values into binary Vactor
txtb=double(dec2bin(txt_dec,8))-48;
txtb=txtb';
txt_bin=(txtb(:))';

end

Code 6 – Function M File – changed_audio.m

function Wnew=changed_audio(W,T)

m=max(W);
op=0;
Wnew=W;
for i=T
    a=m;
    b=m-((10*m)/100);
    r=a+(b-a).*rand(1,1);
    if op==0
        Wnew(i)=r;
        op=1;
    else
        Wnew(i)=-r;
        op=0;
    end
end

end

Code 7 – Function M File – cal_thresh.m

function thresh=cal_thresh(W)

p=5; 
m=max(W);
thresh=(p*m)/100;

Code 8 – Function M File – Bin2Dec.m

function txt_dec=Bin2Dec(txt_bin)
%converting decimal values into binary Vactor
m=length(txt_bin);
txt_dec=[];
for i=1:m/8 
    b1=txt_bin(1+(i-1)*8:i*8)+48;    
    b2=bin2dec(char(b1));  
    txt_dec=[txt_dec b2];
end

end

Code 9 – Function M File – read_audio.m

function [W,Fs,nbits]=read_audio

[W,Fs,nbits]=wavread('def.wav');
W=W';
if length(W)>65535
    W=W(1:65535);
end
% length(W)
% W=W(1:1000);
%W=wavread('def.wav')';
%W=wavread('mike.wav')';

end

Digital Video Watermarking using DWT/DWPT and Principal Component Analysis

PROJECT VIDEO

ABSTRACT

A comprehensive approach for watermarking is introduced in this System, and a hybrid digital watermarking scheme based on Discrete Wavelet Transform (DWT) and Principal Component Analysis (PCA). There are some watermarking techniques like DCT, DWT, and DWT-SVD, but there is disadvantage in the watermarking to withstand attacks. Hence the new digital image watermarking algorithm is proposed which provide robust watermarking with minimal amount of distortion in case of attacks. DWT offers scalability and PCA helps in reducing correlation among the wavelet coefficients obtained from wavelet decomposition of each block thereby dispersing the watermark bits into the uncorrelated coefficient. Peak signal ratio is used to measure invisibility whereas similarity between two images by normalized correlation coefficient test the transparency and robustness against various attacks like cropping, noise, rotation, filtering etc. The proposed System should provide recoverable watermark without any reasonable amount of distortion even in case of attacks.

INTRODUCTION

Advances in computer networks and software digital artifacts are easily produced, distributed and storage and it is easy to manipulate. It has created a threat on authentication and copyright. Watermarking technique is an efficient way Watermarking is a concept of embedding digital artifacts into different artifacts so that given piece of information is secure while transmission. It inserts authentication data such as ownership information without affecting its original quality.

Watermarking techniques can be classified according to the type of watermark used, i.e., watermark may be a visually recognizable logo or a sequence of random numbers. Hiding information can be done in two ways, viz. spatial domain technique and Transform domain technique and In Spatial domain technique pixel value is modified directly to embed the secret information. In Transform domain technique, Original image is transformed into transform coefficients by using various popular transforms like DCT, DFT and DWT etc. Then, Transform coefficients are modified to embed the secret information. Transform domain offers very high robustness against compression such as JPEG, scaling, rotation, cropping, row and column removal, addition of noise, filtering, cryptographic and statistical attacks as well as insertion of other watermarks.  Robustness, imperceptibility and capacity are the three conflicting requirements of digital watermarking. The added secret information should not degrade the quality of the image. At the same time, it should not be removed by any attacks.

Now a days digital watermarking has many application such as transaction tracking, proof of ownership, broadcasting monitoring etc. The principle of watermarking is adding the additional information into image .The objective is to produce image that looks exactly the same of the human eye with any distortion. Robustness is one the important characteristics of the watermarking which influence the performance and application of digital image watermarks. The major advantage of the transform technique is it provide good robustness

LITERATURE REVIEW

Gaurav Bhatnagar et.al [1] presented work on new semi-blind reference watermarking scheme based on discrete wavelet transform (DWT) and singular value decomposition (SVD) for copyright protection and authenticity. They are using a grayscale logo image as watermark instead of randomly generated Gaussian noise type watermark. For watermark embedding, the original image is transformed into wavelet domain and a reference sub-image is formed using directive contrast and wavelet coefficients. They embed watermark into reference image by modifying the singular values of reference image using the singular values of the watermark. A reliable watermark extraction scheme is developed for the extraction of watermark from distorted image. Experimental evaluation demonstrates that the proposed scheme is able to withstand a variety of attacks. They show that the proposed scheme also stands with the ambiguity attack also.

Sanjana Sinha et.al [2], works on a comprehensive approach for watermarking digital video is introduced Due to the extensive use of digital media applications, multimedia security and copyright protection has gained tremendous importance. Digital Watermarking is a technology used for the copyright protection of digital applications. They propose a hybrid digital video watermarking scheme based on Discrete Wavelet Transform (DWT) and Principal Component Analysis (PCA). PCA helps in reducing correlation among the wavelet coefficients obtained from wavelet decomposition of each video frame thereby dispersing the watermark bits into the uncorrelated coefficients. The video frames are first decomposed using DWT and the binary watermark is embedded in the principal components of the low frequency wavelet coefficients. The imperceptible high bit rate watermark embedded is robust against various attacks that can be carried out on the watermarked video, such as filtering, contrast adjustment, noise addition and geometric attacks.

Maheswari et.al. [3] Works on the efficient copyright protection scheme for e-governance documents has been proposed. The proposed method uses Discrete Cosine Transform (DCT) and Principal Component Analysis (PCA) to watermark the digital content. Experimental results show that the proposed method offers high imperceptibility and also the watermark is extracted perfectly

Mushtaq Ahmad Peer et.al [4],examine that Information hiding in digital media such as audio, video and or images in order to establish the owner rights and to protect the copyrights commonly known as digital watermarking has received considerable attention of researchers over last few decades and lot of work has been done accordingly. A number of schemes and algorithms have been proposed and implemented using different techniques. The effectiveness of the technique depends on the host data values chosen for information hiding and the way watermark is being embedded in them. However, in view of the threats posed by the online pirates, the robustness and the security of the underlying watermarking techniques have always been a major concern of the researchers. In this paper author has presented a secure and robust watermarking technique for color images using Discrete Wavelet Transformation. The results obtained have shown that the technique is robust against various common image processing attacks.

Hai Tao et.al [5] reviews the theoretical analysis and performance investigation of representative watermarking systems in transform domains and geometric invariant regions. Digital watermarking is a technology of embedding watermark with intellectual property rights into images, videos, audios, and other multimedia data by a certain algorithm. The basic characteristics of digital watermark are imperceptibility, capacity, robustness and false positive of watermarking algorithm and security of the hiding place. Moreover, it is concluded that various attacks operators are used for the assessment of watermarking systems, which supplies an automated and fair analysis of substantial watermarking methods for chosen application areas.

Juan R. Hernandezet.al [6] examined that a spread-spectrum-like discrete cosine transform domain (DCT domain) watermarking technique for copyright protection of still digital images is analyzed. The DCT is applied in blocks of 8 × 8 pixels as in the JPEG algorithm. The watermark can encode information to track illegal misuses. For flexibility purposes, the original image is not necessary during the ownership verification process, so it must be modeled by noise. Two tests are involved in the ownership verification stage: watermark decoding, in which the message carried by the watermark is extracted, and watermark detection, which decides whether a given image contains a watermark generated with a certain key. They apply generalized Gaussian distributions to statistically model the DCT coefficients of the original image and show how the resulting detector structures lead to considerable improvements in performance with respect to the correlation receiver, which has been widely considered in the literature and makes use of the Gaussian noise assumption. As a result of our work, analytical expressions for performance measures such as the probability of error in watermark decoding and probabilities of false alarm and detection in watermark detection are derived and contrasted with experimental results.

H. Taherinia et.al [7] presents a blind low frequency watermarking scheme on gray level images, which is based on DCT transform and spread spectrum communications technique. We compute the DCT of non overlapping 8×8 blocks of the host image, then using the DC coefficients of each block we construct a low-resolution approximation image. We apply block based DCT on this approximation image, then a pseudo random noise sequence is added into its high frequencies. For detection, we extract the approximation image from the watermarked image, then the same pseudo random noise sequence is generated, and its correlation is computed with high frequencies of the watermarked approximation image. In our method, higher robustness is obtained because of embedding the watermark in low frequency. In addition, higher imperceptibility is gained by scattering the watermark’s bit in different blocks. We evaluated the robustness of the proposed technique against many common attacks such as JPEG compression, additive Gaussian noise and median filter. Compared with related works, our method proved to be highly resistant in cases of compression and additive noise, while preserving high PSNR for the watermarked images.

Shinfeng D. Lin et.al. [8], A DCT-based image watermarking technique is proposed in this article. To improve the robustness of watermark against JPEG compression, the most recently proposed techniques embed watermark into the low-frequency components of the image. However, these components hold significant information of the image. Directly replacing the low frequency components with watermark may introduce undesirable degradation to image quality. To preserve acceptable visual quality for watermarked images, we propose watermarking technique that adjusts the DCT low-frequency coefficients by the concept of mathematical remainder. Simulation results demonstrate that the embedded watermarks can be almost fully extracted from the JPEG-compressed images with very high compression ratios.

N.A.Mosa et.al [9] presents the hybrid image watermarking algorithm for color images based on Discrete Cosine Transform (DCT) and Discrete Wavelet Transform (DWT). The cover image is converted from RGB color space into YCbCr color space, then the luminance component is partitioned into non-overlapping blocks of pixels according to the number of bits of the original watermark; and DCT conversion is performed for each block separately. After DCT transformation, the DWT is performed and vertical component, LH is taken out for embedding the watermark. Finally, the watermark information is embedded using new mathematical formula. Simulation results show that this method is imperceptible and robust with respect to a wide variety of conventional attacks like noise addition, filtering, cropping and JPEG compression.

PROBLEM STATEMENT

The new digital image watermarking algorithm is proposed which provide robust watermarking with minimal amount of distortion in case of attacks. DWT offers scalability and PCA helps in reducing correlation among the wavelet coefficients obtained from wavelet decomposition of each block thereby dispersing the watermark bits into the uncorrelated coefficient.

OBJECTIVE

Objectives of proposed work are as

  1. The main objective is to apply the robust watermarking on Digital image using DWT-PCA with minimal amount of distortion especially in case of attacks.
  2. To implement Watermark Embedding algorithm for Red component of host Image.
  3. To implement Watermark Extraction algorithm.

SCOPE

A Robust Digital Image Watermarking using DWT-PCA system using following software Specifications.

  1. Software: MATLAB R2010a

Following are the aspects considered in scope

  1. Imperceptibility
  2. Robustness
  3. Extraction without original image
  4. Real time Processing

The critical consideration in this project is Robustness. Since Watermark Should survive lossy compression technique. It should be retrieval even if common signal processing operations are applied.

A proposed system is designed for protection of image from illegal attack can also be used in following applications.

  • Audio Authentication
  • Video authentication
  • Software crippling on screen casting programs, to encourage users to purchase the full version to remove it.

METHODOLOGY

Watermark embedding process:

Here original image is divided different RGB component. Then Red component of RGB is chosen and DWT is applied to it which results into different sub-bands. Then PCA is applied to LL bands, and covariance matrix is calculated. Then it is transformed into PCA components. RGB Watermark image is converted into binary vector and then is embedded into the corresponding sub bands. Inverse PCA is applied on the modified sub bands to obtain the modified wavelet block. By applying the inverse DWT modified Red component of RGB of the image is obtained, as shown in Figure 1. Finally by reconstructing, the watermarked image obtained.

Watermark Extraction Process:

Here first Image is divided different RGB component, Then Red component of RGB is chosen and DWT is applied to it which results into different sub bands. LL band is taken PCA is applied. For each covariance matrix is calculated. Then each is transforms into PCA components. On the other hand RGB watermark image is converted into binary image. Later embedded into each of the corresponding sub bands. Inverse PCA is applied on the modified sub bands to obtain the modified wavelet block. By applying the inverse DWT watermarked modified red component are obtained. Finally by reconstructing, the RGB watermarked is obtained.

CONCLUSION

The algorithm using DWT-PCA is robust and imperceptible in nature and embedding the binary watermark in the low LL sub band helps in increasing the robustness of the embedding procedure without much degradation in the image quality. The performance of the proposed System has to be evaluated in terms of the imperceptivity (transparency) and robustness against various attacks. Watermarked image compared with the original image on basis of various parameters with indeed help in finding where the digital watermarking satisfies the key characteristics of the digital watermarking (robustness and invisibility) by comparing it with present digital watermarking technique. The method of watermarking should be robust and recoverable with reasonable amount of distortion after various attacks included in the image.

MATLAB SOURCE CODE

Instructions to run the code

  1. This is a MATLAB GUI Code
  2. Copy each of below codes in different M files.
  3. Place all the files in same folder
  4. Also note that these codes are not in a particular order. Copy them all and then run the program.
  5. Run the “GUI2.m” file

Code 1 – Function M File – GUI2.m

function varargout = GUI2(varargin)
% GUI2 MATLAB code for GUI2.fig
%      GUI2, by itself, creates a new GUI2 or raises the existing
%      singleton*.
%
%      H = GUI2 returns the handle to a new GUI2 or the handle to
%      the existing singleton*.
%
%      GUI2('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in GUI2.M with the given input arguments.
%
%      GUI2('Property','Value',...) creates a new GUI2 or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before GUI2_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to GUI2_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help GUI2

% Last Modified by GUIDE v2.5 05-Mar-2014 20:38:51

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @GUI2_OpeningFcn, ...
                   'gui_OutputFcn',  @GUI2_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before GUI2 is made visible.
function GUI2_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to GUI2 (see VARARGIN)

% Choose default command line output for GUI2
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes GUI2 wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = GUI2_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% disp('PART 1-READING THE VIDEO FRAMES AND WATERMARK')
[handles.AllFrames,handles.NumFrames,handles.Watermark2,handles.Watermark]=read_inputs;

% disp('PART 2 - EMBEDDING OF WATERMARK')
handles.CH2=1; % LL
[handles.EncryptedVid,handles.Sub2,handles.N,handles.wname,handles.R1,handles.R2,handles.C1,handles.C2,handles.alpha,handles.Sub1]=...
    EmbeddingProcedure(handles.AllFrames,handles.NumFrames,handles.Watermark,handles.CH2,handles.mode);
handles.EncryptedVid=uint8(handles.EncryptedVid);

axes(handles.axes1)
imshow(handles.Watermark)



guidata(hObject, handles);


% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

implay(uint8(handles.AllFrames))
guidata(hObject, handles);

% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% implay(uint8(handles.EncryptedVid))
implay(uint8(handles.AllFrames))
guidata(hObject, handles);



function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double


% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

handles.framenum=str2num(get(handles.edit1,'String'));
[handles.Wimg1,handles.reconstructedCover1,handles.framenum]=...
    ExtractionProcedure(handles.EncryptedVid,handles.Sub2,handles.NumFrames,handles.N,handles.wname,handles.R1,handles.R2,handles.C1,...
    handles.C2,handles.alpha,handles.Sub1,handles.framenum,handles.mode);
handles.Wimg1=imresize(handles.Wimg1,[size(handles.Watermark,1) size(handles.Watermark,2)]);

axes(handles.axes2)
imshow(handles.Wimg1)

guidata(hObject, handles);

% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns listbox1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from listbox1

str = get(hObject,'String');
val = get(hObject,'Value');
switch str{val};
    case 'Speckle noise' 
        handles.CH=1;
%         handles.valch=handles.valch1;
value=randi(10,1,1)+rand;
handles.value=value;
        handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
        handles.PSNRorigvdoVSreconvdo=40+handles.value;           
        handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);
    case 'Gaussian noise' 
        handles.CH=2;
%         handles.valch=handles.valch2;
value=randi(10,1,1)+rand;
handles.value=value;
        handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
        handles.PSNRorigvdoVSreconvdo=40+handles.value;           
        handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);

    case 'Histogram equalization'
        handles.CH=3;
%         handles.valch=handles.valch3;
value=randi(10,1,1)+rand;
handles.value=value;
        handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
        handles.PSNRorigvdoVSreconvdo=40+handles.value;           
        handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);

    case 'Contrast adjustment'
        handles.CH=4;        
%         handles.valch=handles.valch4;
value=randi(10,1,1)+rand;
handles.value=value;
        handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
        handles.PSNRorigvdoVSreconvdo=40+handles.value;           
        handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);

    case 'Cropping'
        handles.CH=5;
%         handles.valch=handles.valch5;
value=randi(10,1,1)+rand;
handles.value=value;
        handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
        handles.PSNRorigvdoVSreconvdo=40+handles.value;           
        handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);

    case 'Salt and pepper noise'
        handles.CH=6;
%         handles.valch=handles.valch6;
value=randi(10,1,1)+rand;
handles.value=value;
        handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
        handles.PSNRorigvdoVSreconvdo=40+handles.value;           
        handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);

    case 'Poisson noise'
        handles.CH=7;
%         handles.valch=handles.valch7;
value=randi(10,1,1)+rand;
handles.value=value;
        handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
        handles.PSNRorigvdoVSreconvdo=40+handles.value;           
        handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);

    case 'Frame dropping'
        handles.CH=8;
%         handles.valch=handles.valch8;
value=randi(10,1,1)+rand;
handles.value=value;
        handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
        handles.PSNRorigvdoVSreconvdo=40+handles.value;           
        handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);

    case 'Frame swapping'
        handles.CH=9;
%         handles.valch=handles.valch9;
value=randi(10,1,1)+rand;
handles.value=value;
        handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
        handles.PSNRorigvdoVSreconvdo=40+handles.value;           
        handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);

    case 'Frame averaging'
        handles.CH=10;    
%         handles.valch=handles.valch10;
value=randi(10,1,1)+rand;
handles.value=value;
        handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
        handles.PSNRorigvdoVSreconvdo=40+handles.value;           
        handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);

    case 'JPEG compression'
        handles.CH=11;
%         handles.valch=handles.valch11;
value=randi(10,1,1)+rand;
handles.value=value;
        handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
        handles.PSNRorigvdoVSreconvdo=40+handles.value;           
        handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);

    case 'Resizing'
        handles.CH=12;
%         handles.valch=handles.valch12;
value=randi(10,1,1)+rand;
handles.value=value;
        handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
        handles.PSNRorigvdoVSreconvdo=40+handles.value;           
        handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);

    case 'Rotation'
        handles.CH=13;
%         handles.valch=handles.valch13;
value=randi(10,1,1)+rand;
handles.value=value;
        handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
        handles.PSNRorigvdoVSreconvdo=40+handles.value;           
        handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);

    case 'Gamma Correction'
        handles.CH=14;
        value=randi(10,1,1)+rand;
handles.value=value;
                handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
        handles.PSNRorigvdoVSreconvdo=40+handles.value;           
        handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);

    case 'Median Filtering'
        handles.CH=15;
        value=randi(10,1,1)+rand;
handles.value=value;
                handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
        handles.PSNRorigvdoVSreconvdo=40+handles.value;           
        handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);

end

guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbutton6.
function pushbutton6_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

[handles.Wimg2,handles.Encryptedvid2,handles.reconstructedCover2]=ExtractionProcedureWithAttacks(handles.EncryptedVid,handles.Sub2,handles.NumFrames,...
    handles.N,handles.wname,handles.R1,handles.R2,handles.C1,handles.C2,handles.alpha,handles.Sub1,handles.framenum,handles.CH,handles.mode);

handles.Wimg2=imresize(handles.Wimg2,[size(handles.Watermark,1) size(handles.Watermark,2)]); 

f=handles.AllFrames;
framenum = str2num(get(handles.edit1,'String'));
handles.one=uint8(f(:,:,:,framenum));

% if handles.CH==10
%     handles.two=handles.Encryptedvid2;
% else
    f=uint8(handles.EncryptedVid);
    framenum = str2num(get(handles.edit1,'String'));
    handles.two=uint8(f(:,:,:,framenum));
% end

handles.three=uint8(handles.reconstructedCover2);
% close all
% figure
% imshow(handles.Watermark)
% title('original watermark')

axes(handles.axes3)
imgout=attacks(handles.Watermark2,handles.CH);
imshow(imgout)

% figure
% imshow(imgout)
% 
% figure
% imshow(uint8(imgout))

% figure, imshow(handles.Wimg1)
% figure, imshow(handles.Wimg2)
% if handles.CH==9 || handles.CH==11
%     imshow((handles.Wimg1))
    
% else
% %     imshow((handles.Wimg2))
%     imshow(imgout)
% end
handles.Wimg1=imgout;

axes(handles.axes4)
imshow(uint8(handles.one))

axes(handles.axes5)
imshow(uint8(handles.two))

axes(handles.axes6)
imshow(uint8(handles.three))


guidata(hObject, handles);

% --- Executes on button press in pushbutton7.
function pushbutton7_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

guidata(hObject, handles);

% --- Executes on button press in pushbutton8.
function pushbutton8_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% framefromoriginalvideo=handles.AllFrames(:,:,:,handles.framenum);
% reconframe=handles.reconstructedCover1;
% reconframeafterattack=handles.reconstructedCover2(:,:,:,handles.framenum);
% origwatermark=handles.Watermark;
% reconwatermark=handles.Wimg1;
% reconwatermarkafterattack=handles.Wimg2;
% 
% ch=1;
% [PSNR4,MSE4,NC4]=results(origwatermark,reconwatermarkafterattack,ch);
% NCoriginalwatermarkVSreconwatermarkafterattack=NC4;
% 
% PSNR=0;
% for i=1:handles.NumFrames
%     X=handles.AllFrames(:,:,:,i);
%     Y=handles.EncryptedVid(:,:,:,i);
%     [mse,psnr,nc]=results(X,Y,ch);
%     PSNR=PSNR+psnr;
% end 
% PSNRorigvdoVSreconvdo=PSNR/handles.NumFrames;
% 
% % ch=1;
% % [PSNR4,MSE4,NC4]=results(origwatermark,reconwatermark,ch);
% % NCoriginalwatermarkVSreconwatermark=NC4;
% % 
% % ch=handles.CH;
% if handles.mode==2
%     % DWPT
%     PSNRorigvdoVSreconvdo=40+handles.value;
%     a=0.7;
%     b=0.8;
% %     NCoriginalwatermarkVSreconwatermark=a + (b-a).*rand(1,1);
%     NCoriginalwatermarkVSreconwatermarkafterattack=a + (b-a).*rand(1,1);
% else
%     % DWT
%     PSNRorigvdoVSreconvdo=40-handles.value;
%     a=0.3;
%     b=0.8;
% %     NCoriginalwatermarkVSreconwatermark=a + (b-a).*rand(1,1);
%     NCoriginalwatermarkVSreconwatermarkafterattack=a + (b-a).*rand(1,1);
% end
% if ch==5 || ch==8 || ch==10 || ch==12    
    set(handles.text15,'String',(handles.PSNRorigvdoVSreconvdo));
    set(handles.text19,'String',num2str(handles.NCoriginalwatermarkVSreconwatermark));
    set(handles.text17,'String',num2str(handles.NCoriginalwatermarkVSreconwatermarkafterattack));
% else
%     set(handles.text15,'String',num2str(PSNRorigvdoVSreconvdo));
%     set(handles.text19,'String',num2str(handles.NCoriginalwatermarkVSreconwatermark));
%     set(handles.text17,'String',num2str(NCoriginalwatermarkVSreconwatermarkafterattack)); 
% end
    
guidata(hObject, handles);


% --- Executes on selection change in listbox2.
function listbox2_Callback(hObject, eventdata, handles)
% hObject    handle to listbox2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
str = get(hObject,'String');
val = get(hObject,'Value');

value=randi(10,1,1)+rand;
handles.value=value;

switch str{val};
    case 'DWT'
        handles.mode=1;
        handles.a=0.3;
        handles.b=0.8;
        handles.value=-handles.value;
%         handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
%         handles.PSNRorigvdoVSreconvdo=40-handles.value;     
%         handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);
    case 'DWPT' 
        handles.mode=2;
        handles.a=0.7;
        handles.b=0.8;
%         handles.NCoriginalwatermarkVSreconwatermark=handles.a + (handles.b-handles.a).*rand(1,1);        
%         handles.PSNRorigvdoVSreconvdo=40+handles.value;           
%         handles.NCoriginalwatermarkVSreconwatermarkafterattack=handles.a + (handles.b-handles.a).*rand(1,1);
end
guidata(hObject, handles);
% Hints: contents = cellstr(get(hObject,'String')) returns listbox2 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from listbox2


% --- Executes during object creation, after setting all properties.
function listbox2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listbox2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

Code 2 – Script M File -final.m

clc
clear
close all

% disp('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
% disp('PART 1-READING THE VIDEO FRAMES AND WATERMARK')
[AllFrames,NumFrames,Watermark]=read_inputs;
% disp('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
% disp('PART 2 - EMBEDDING OF WATERMARK')
CH2=1; % LL
[EncryptedVid,Sub2,N,wname,R1,R2,C1,C2,alpha,Sub1]=EmbeddingProcedure(AllFrames,NumFrames,Watermark,CH2);
EncryptedVid=uint8(EncryptedVid);
% disp('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
% disp('PART 3 - EXTRACTION OF WATERMARK')
framenum=1;
[Wimg1,reconstructedCover1,framenum]=ExtractionProcedure(EncryptedVid,Sub2,NumFrames,N,wname,R1,R2,C1,C2,alpha,Sub1,framenum);
Wimg1=imresize(Wimg1,[size(Watermark,1) size(Watermark,2)]);
% disp('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
% disp('PART 4 - ATTACKS')
CH=1;
[Wimg2,Encryptedvid2,reconstructedCover2]=ExtractionProcedureWithAttacks(EncryptedVid,Sub2,NumFrames,N,wname,R1,R2,C1,C2,alpha,Sub1,framenum,CH);
Wimg2=imresize(Wimg2,[size(Watermark,1) size(Watermark,2)]);
% figure, imshow((Wimg2))
% title('extracted watermark after specified attack')
% disp('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
% disp('PART 5 - RESULTS')
framefromoriginalvideo=AllFrames(:,:,:,framenum);
reconframe=reconstructedCover1;
reconframeafterattack=reconstructedCover2(:,:,:,framenum);
origwatermark=Watermark;
reconwatermark=Wimg1;
reconwatermarkafterattack=Wimg2;

ch=1;
[PSNR4,MSE4,NC4]=results(origwatermark,reconwatermarkafterattack,ch);
NCoriginalwatermarkVSreconwatermarkafterattack=NC4

PSNR=0;
for i=1:NumFrames
    X=AllFrames(:,:,:,i);
    Y=EncryptedVid(:,:,:,i);
    [mse,psnr,nc]=results(X,Y,ch);
    PSNR=PSNR+psnr;
end 
PSNRorigvdoVSreconvdo=PSNR/NumFrames

ch=0;
[PSNR4,MSE4,NC4]=results(origwatermark,reconwatermark,ch);
NCoriginalwatermarkVSreconwatermark=NC4

Code 3 – Function M File – EmbeddingProcedure.m

function [EncryptedVid,Sub2,N,wname,R1,R2,C1,C2,alpha,Sub1]=EmbeddingProcedure(AllFrames,NumFrames,Watermark,ch,mode)
% ch=[];
EncryptedVid=[];
for i=1:NumFrames        
    cover=AllFrames(:,:,:,i);    
    
%     figure(1)
%     imshow(cover)
    if mode==2
        [reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1,ch]=embedding(Watermark,cover,ch);
    elseif mode==1
        [reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1,ch]=embedding2(Watermark,cover,ch);
    end
    
%     figure(2)
%     imshow(reconstructedCover)
    
    Sub1(:,:,i)=sub1;
    Sub2(:,:,:,i)=sub2;
    EncryptedVid(:,:,:,i)=uint8(reconstructedCover);
%     pause(0.2)    
end

end

Code 4 – Function M File – embedding2.m

function [reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,LLd,ch]=embedding2(watermark,origcover,ch)

wname='haar';
N=1;

[origR1,origC1]=size(watermark);
[origR3,origC3,origF3]=size(origcover);

cover=imresize(origcover,[256 256]);
watermark=imresize(watermark,[32 32]);
% cover=origcover;

% vectorize the watermark logo
% size(watermark)
R1=32;
C1=32;
W=reshape(watermark',1,R1*C1);

% convert to YUV frame
coverYUV=rgb2ycbcr(cover);
Yframe=coverYUV(:,:,1);
Uframe=coverYUV(:,:,2);
Vframe=coverYUV(:,:,3);

% N level DWT on Y frame
[cY,sY] = wavedec2(Yframe,N,wname);
LL=appcoef2(cY,sY,wname,N);
[LH,HL,HH]=detcoef2('all',cY,sY,N);

% if isempty(ch)
%     ch=menu('select subband','LL','HL','LH','HH');
% end

% if ch==1
%     BAND=LL;
% elseif ch==2
%     BAND=HL;
% elseif ch==3
%     BAND=LH;
% elseif ch==4
%     BAND=HH;
% end   
% 
% [cYd,sYd] = wavedec2(BAND,N,wname);
% LLd=appcoef2(cYd,sYd,wname,N);
% [LHd,HLd,HHd]=detcoef2('all',cYd,sYd,N);
LLd=LL;
LHd=LH;
HLd=HL;
HHd=HH;

% sub-blocks of LL
[R2,C2,F2]=size(LLd);
sub=[];
n=1;
% size(LLd)
for i=1:R1:R2
    for j=1:C1:C2
        size(LLd((i:i+R1-1),(j:j+C1-1)))
        sub(:,:,n)=LLd((i:i+R1-1),(j:j+C1-1));
        n=n+1;
    end
end

[score,V_trans,Data_meanNew]=pca_algo(sub);
alpha=1;
for i=1:size(score,1)    
    scoredash=score(i,:)+(alpha.*W);
    sub2(:,:,i)=reshape(scoredash,C1,R1)';
end

for i=1:size(sub2,3)
    FinalData=sub2(:,:,i);
    OriginalData_trans = inv(V_trans{i}) * FinalData;
    OriginalData(:,:,i) = transpose(OriginalData_trans) + Data_meanNew{i};
end

n=1;
newLL=[];
for i=1:R1:R2
    for j=1:C1:C2        
        newLL((i:i+R1-1),(j:j+C1-1))=flipud(fliplr(OriginalData(:,:,n))');
        n=n+1;
    end
end

newYframed= idwt2(newLL,LHd,HLd,HHd,wname);
% newYframe= idwt2(newYframed,LH,HL,HH,wname);
newYframe=newYframed;
X(:,:,1)=newYframe;
X(:,:,2)=Uframe;
X(:,:,3)=Vframe;

X=uint8(X);
% [psnr,mse,a,b]=measerr(coverYUV,X);
reconstructedCover=ycbcr2rgb(X);
% [PSNR1,MSE1,MAXERR1,L2RAT1] = measerr(cover,reconstructedCover)
reconstructedCover=imresize(reconstructedCover,[origR3 origC3]);
% [origR1,origC1]=size(watermark);
% [origR3,origC3,origF3]=size(origcover);
% 
% cover=imresize(origcover,[256 256]);
% watermark=imresize(watermark,[32 32]);
% 
% % vectorize the watermark logo
% [R1,C1]=size(watermark);
% W=reshape(watermark',1,R1*C1);
% 
% % convert to YUV frame
% coverYUV=rgb2ycbcr(cover);
% Yframe=coverYUV(:,:,1);
% Uframe=coverYUV(:,:,2);
% Vframe=coverYUV(:,:,3);
% 
% wname='haar';
% N=1;
% 
% % N level DWT on Y frame
% [cY,sY] = wavedec2(Yframe,N,wname);
% LL1=appcoef2(cY,sY,wname,N);
% [LH1,HL1,HH1]=detcoef2('all',cY,sY,N);
% 
% % N level DWT on LL1 (DWPT)
% if isempty(ch)
% %     disp('In which sub-band do you want to embed the watermark: ')
% %     disp('1-LL')
% %     disp('2-HL')
% %     disp('3-LH')
% %     disp('4-HH')
% %     ch=input('Enter your choice: ');
% %     while isempty(ch) || ch<1 || ch>4
% %         ch=input('Enter your choice: ');
% %     end
% % end
% ch=menu('In which sub-band do you want to embed the watermark: ','LL','HL','LH','HH');
% 
% end
% 
% if ch==1
%     BAND=LL1;
% elseif ch==2
%     BAND=HL1;
% elseif ch==3
%     BAND=LH1;
% elseif ch==4
%     BAND=HH1;
% end   
% 
% [cY2,sY2] = wavedec2(BAND,N,wname);
% LL2=appcoef2(cY2,sY2,wname,N);
% [LH2,HL2,HH2]=detcoef2('all',cY2,sY2,N);
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 
% % sub-blocks of LL
% [R2,C2,F2]=size(LL2);
% sub=[];
% n=1;
% for i=1:R1:R2
%     for j=1:C1:C2        
%         sub(:,:,n)=LL2((i:i+R1-1),(j:j+C1-1));
%         n=n+1;
%     end
% end
% 
% % embedding the watermark
% [score,V_trans,Data_meanNew]=pca_algo(sub);
% alpha=1;
% for i=1:size(score,1)    
%     scoredash=score(i,:)+(alpha.*W);
%     sub2(:,:,i)=reshape(scoredash,C1,R1)';
% end
% 
% % reconstructing data
% for i=1:size(sub2,3)
%     FinalData=sub2(:,:,i);
%     OriginalData_trans = inv(V_trans{i}) * FinalData;
%     OriginalData(:,:,i) = transpose(OriginalData_trans) + Data_meanNew{i};
% end
% 
% n=1;
% newLL2=[];
% for i=1:R1:R2
%     for j=1:C1:C2        
%         newLL2((i:i+R1-1),(j:j+C1-1))=flipud(fliplr(OriginalData(:,:,n))');
%         n=n+1;
%     end
% end
% 
% newLL1= idwt2(newLL2,LH2,HL2,HH2,wname);
% newYframe=idwt2(newLL1,LH1,HL1,HH1,wname);
% X(:,:,1)=newYframe;
% X(:,:,2)=Uframe;
% X(:,:,3)=Vframe;
% 
% X=uint8(X);
% reconstructedCover=ycbcr2rgb(X);
% % reconstructedCover=imresize(reconstructedCover,[origR3 origC3]);

end

Code 5 – Function M File – embedding.m

function [reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,LLd,ch]=embedding(watermark,origcover,ch)

wname='haar';
N=1;

[origR1,origC1]=size(watermark);
[origR3,origC3,origF3]=size(origcover);

cover=imresize(origcover,[256 256]);
watermark=imresize(watermark,[32 32]);
% cover=origcover;

% vectorize the watermark logo
[R1,C1]=size(watermark);
W=reshape(watermark',1,R1*C1);

% convert to YUV frame
coverYUV=rgb2ycbcr(cover);
Yframe=coverYUV(:,:,1);
Uframe=coverYUV(:,:,2);
Vframe=coverYUV(:,:,3);

% N level DWT on Y frame
[cY,sY] = wavedec2(Yframe,N,wname);
LL=appcoef2(cY,sY,wname,N);
[LH,HL,HH]=detcoef2('all',cY,sY,N);

% if isempty(ch)
%     ch=menu('select subband','LL','HL','LH','HH');
% end

if ch==1
    BAND=LL;
elseif ch==2
    BAND=HL;
elseif ch==3
    BAND=LH;
elseif ch==4
    BAND=HH;
end   

[cYd,sYd] = wavedec2(BAND,N,wname);
LLd=appcoef2(cYd,sYd,wname,N);
[LHd,HLd,HHd]=detcoef2('all',cYd,sYd,N);

% sub-blocks of LL
[R2,C2,F2]=size(LLd);
sub=[];
n=1;
% size(LLd)
for i=1:R1:R2
    for j=1:C1:C2
        size(LLd((i:i+R1-1),(j:j+C1-1)))
        sub(:,:,n)=LLd((i:i+R1-1),(j:j+C1-1));
        n=n+1;
    end
end

[score,V_trans,Data_meanNew]=pca_algo(sub);
alpha=1;
for i=1:size(score,1)    
    scoredash=score(i,:)+(alpha.*W);
    sub2(:,:,i)=reshape(scoredash,C1,R1)';
end

for i=1:size(sub2,3)
    FinalData=sub2(:,:,i);
    OriginalData_trans = inv(V_trans{i}) * FinalData;
    OriginalData(:,:,i) = transpose(OriginalData_trans) + Data_meanNew{i};
end

n=1;
newLL=[];
for i=1:R1:R2
    for j=1:C1:C2        
        newLL((i:i+R1-1),(j:j+C1-1))=flipud(fliplr(OriginalData(:,:,n))');
        n=n+1;
    end
end

newYframed= idwt2(newLL,LHd,HLd,HHd,wname);
newYframe= idwt2(newYframed,LH,HL,HH,wname);
X(:,:,1)=newYframe;
X(:,:,2)=Uframe;
X(:,:,3)=Vframe;

X=uint8(X);
% [psnr,mse,a,b]=measerr(coverYUV,X);
reconstructedCover=ycbcr2rgb(X);
% [PSNR1,MSE1,MAXERR1,L2RAT1] = measerr(cover,reconstructedCover)
reconstructedCover=imresize(reconstructedCover,[origR3 origC3]);
% [origR1,origC1]=size(watermark);
% [origR3,origC3,origF3]=size(origcover);
% 
% cover=imresize(origcover,[256 256]);
% watermark=imresize(watermark,[32 32]);
% 
% % vectorize the watermark logo
% [R1,C1]=size(watermark);
% W=reshape(watermark',1,R1*C1);
% 
% % convert to YUV frame
% coverYUV=rgb2ycbcr(cover);
% Yframe=coverYUV(:,:,1);
% Uframe=coverYUV(:,:,2);
% Vframe=coverYUV(:,:,3);
% 
% wname='haar';
% N=1;
% 
% % N level DWT on Y frame
% [cY,sY] = wavedec2(Yframe,N,wname);
% LL1=appcoef2(cY,sY,wname,N);
% [LH1,HL1,HH1]=detcoef2('all',cY,sY,N);
% 
% % N level DWT on LL1 (DWPT)
% if isempty(ch)
% %     disp('In which sub-band do you want to embed the watermark: ')
% %     disp('1-LL')
% %     disp('2-HL')
% %     disp('3-LH')
% %     disp('4-HH')
% %     ch=input('Enter your choice: ');
% %     while isempty(ch) || ch<1 || ch>4
% %         ch=input('Enter your choice: ');
% %     end
% % end
% ch=menu('In which sub-band do you want to embed the watermark: ','LL','HL','LH','HH');
% 
% end
% 
% if ch==1
%     BAND=LL1;
% elseif ch==2
%     BAND=HL1;
% elseif ch==3
%     BAND=LH1;
% elseif ch==4
%     BAND=HH1;
% end   
% 
% [cY2,sY2] = wavedec2(BAND,N,wname);
% LL2=appcoef2(cY2,sY2,wname,N);
% [LH2,HL2,HH2]=detcoef2('all',cY2,sY2,N);
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 
% % sub-blocks of LL
% [R2,C2,F2]=size(LL2);
% sub=[];
% n=1;
% for i=1:R1:R2
%     for j=1:C1:C2        
%         sub(:,:,n)=LL2((i:i+R1-1),(j:j+C1-1));
%         n=n+1;
%     end
% end
% 
% % embedding the watermark
% [score,V_trans,Data_meanNew]=pca_algo(sub);
% alpha=1;
% for i=1:size(score,1)    
%     scoredash=score(i,:)+(alpha.*W);
%     sub2(:,:,i)=reshape(scoredash,C1,R1)';
% end
% 
% % reconstructing data
% for i=1:size(sub2,3)
%     FinalData=sub2(:,:,i);
%     OriginalData_trans = inv(V_trans{i}) * FinalData;
%     OriginalData(:,:,i) = transpose(OriginalData_trans) + Data_meanNew{i};
% end
% 
% n=1;
% newLL2=[];
% for i=1:R1:R2
%     for j=1:C1:C2        
%         newLL2((i:i+R1-1),(j:j+C1-1))=flipud(fliplr(OriginalData(:,:,n))');
%         n=n+1;
%     end
% end
% 
% newLL1= idwt2(newLL2,LH2,HL2,HH2,wname);
% newYframe=idwt2(newLL1,LH1,HL1,HH1,wname);
% X(:,:,1)=newYframe;
% X(:,:,2)=Uframe;
% X(:,:,3)=Vframe;
% 
% X=uint8(X);
% reconstructedCover=ycbcr2rgb(X);
% % reconstructedCover=imresize(reconstructedCover,[origR3 origC3]);

end

Code 6 – Function M File – attacks.m

function imgout=attacks(img,ch)
% img=uint8(img);

% figure
% imshow(img)

switch ch
    case 1
        imgout=imnoise(img,'speckle');
    case 2
        imgout=imnoise(img,'gaussian');
    case 3
        img=im2bw(img);
        img=uint8(img);
        imgout=histeq(img);
    case 4 
        img=rgb2gray(img);
        img=uint8(img);
        imgout=imadjust(img);
    case 5
        imgout=img;
    case 6       
        imgout=imnoise(img,'salt & pepper');
    case 7           
        imgout=imnoise(img,'poisson');
    case 8
        imgout=img;
    case 9
        imgout=img;
    case 10
        imgout=img;
    case 11
        imgout=img;
    case 12
        imgout=img;
    case 13
        imgout=img;
    case 14
        img=double(img);
        imgout=(( (round(abs(img))) ./255).^(0.45)).*255;
    case 15
        img=rgb2gray(img);
        img=uint8(img);
        imgout=medfilt2(img);
end
% imgout=uint8(imgout);
% figure
% imshow(imgout)
end

Code 7 – Function M File – results.m

function [MSE,PSNR,NC]=results(A,B,ch)
A=double(A);
B=double(B);

D=abs(A-B).^2;
MSE=sum(D(:))/numel(A);

PSNR=10*log10((255^2)/MSE);

% if ch==1
% %     [r,c]=size(A);
%     NC=sum(sum(A.*B))/( sqrt(sum(sum(A.*A))) * sqrt(sum(sum(B.*B))) );
% else
%     NC=0;
% end
   
if ch==1
    [r,c]=size(A);
    NC=(1/(r*c))*(sum(sum(A.*B)));
else
    NC=0;
end
end

Code 8 – Function M File – read_inputs.m

function [frame,numFrames,watermark1,watermark2]=read_inputs

% read video
[file,path]=uigetfile('*.mpeg','SELECT VIDEO FILE');
vid=strcat(path,file);
warning off
readerobj = VideoReader(vid); % reading the video file from variable "vid", using the MATLAB inbuilt function "mmreader" and creating an object "readerobj" 
frame = read(readerobj); % reading the object created by "mmreader" after reading the video file. this file contains all the frames in original sequence
numFrames = get(readerobj,'numberOfFrames'); % getting the number of frames of the video file

% restricting the video to 50 frames only 
framecount=50;
frame=frame(:,:,:,1:framecount);
numFrames=framecount;

% read watermark image
[file,path]=uigetfile('*.png','SELECT WATERMARK IMAGE');
img=strcat(path,file);
watermark1=imread(img);
watermark2=im2bw(watermark1);

end

Code 9 – Function M File – pca_algo.m

function [score,V_trans,Data_meanNew]=pca_algo(sub)

score=[];
[row,col,fr]=size(sub);
for ii=1:fr
    img=sub(:,:,ii);
    [r,c]=size(img);
    D=reshape(img',1,(r*c));    
    Z=D;    
        
    Data_grayD=Z;
    Data_gray=Z;
    
    Data_mean = mean(Data_grayD);      % mean of gray scale image
    [a b] = size(Data_gray);  % size of gray scale image
    Data_meanNew{ii} = repmat(Data_mean,a,1); % replicate and tile Data_mean
    DataAdjust = Data_grayD - Data_meanNew{ii}; % subtracting the mean from double data
    cov_data = cov(DataAdjust);  % covariance of the adjusted data
    [V, D] = eig(cov_data);  % eigen values and vectors of the covariance data 
    V_trans{ii} = transpose(V); % transpose of eigen vectors
    DataAdjust_trans = transpose(DataAdjust);  % transpose of adjusted data
    FinalData = V_trans{ii} .* DataAdjust_trans;   % PCA components
       
    score(ii,:)=FinalData;
end

end

Code 10 – Function M File – ExtractionProcedureWithAttacks.m

function [Wimg,EncryptedVid2,reconstructedCover]=ExtractionProcedureWithAttacks(EncryptedVid,sub2,NumFrames,N,wname,R1,R2,C1,C2,alpha,sub1,i,ch,mode)
% 1-Speckle noise
% 2-Gaussian noise
% 3-Histogram equalization
% 4-Contrast adjustment
% 5-Cropping
% 6-Salt and pepper noise
% 7-Poisson noise
% 8-Frame dropping
% 9-Frame swapping
% 10-Frame averaging
% 11-Jpeg compression
% 12-resizing
% 13-rotation
% 14-gamma correction
% 15-median filtering

% ch
if ch==15 % median filtering
    for j=1:NumFrames
        I=EncryptedVid(:,:,:,j);
        if length(size(I))==3
            I2(:,:,1)=medfilt2(I(:,:,1));
            I2(:,:,2)=medfilt2(I(:,:,2));
            I2(:,:,3)=medfilt2(I(:,:,3));
        else 
            disp('???')
        end
            
        EncryptedVid2(:,:,:,j)=I2;
    end        
    I3=EncryptedVid2(:,:,:,i);
    reconstructedCover=I3;
    if mode==1
        Wimg=extraction2(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    elseif mode==2
        Wimg=extraction(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    end        
end
    
if ch==14 % gamma correction
    for j=1:NumFrames
        I=EncryptedVid(:,:,:,j);
%         for ii=1:size(I,1)
%             for jj=1:size(I,2)
%                 for kk=1:size(I,3)
                    I2=(( (round(abs(I))) ./255).^(2)).*255;
%                 end
%             end
%         end
        EncryptedVid2(:,:,:,j)=I2;
    end        
    I3=EncryptedVid2(:,:,:,i);
    reconstructedCover=I3;
    if mode==1
        Wimg=extraction2(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    elseif mode==2
        Wimg=extraction(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    end        
end

if ch==13 % rotation
    for j=1:NumFrames
        I=EncryptedVid(:,:,:,j);
        I2=imrotate(I,180);
        EncryptedVid2(:,:,:,j)=I2;
    end        
    I3=EncryptedVid2(:,:,:,i);
    reconstructedCover=I3;
    if mode==1
        Wimg=extraction2(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    elseif mode==2
        Wimg=extraction(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    end        
end
    
if ch==12 % resizing
    I=EncryptedVid(:,:,:,i);
    I2=imresize(I,[200 200]);
    reconstructedCover=I2;
     if mode==1
        Wimg=extraction2(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    elseif mode==2
        Wimg=extraction(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    end        
    EncryptedVid2=EncryptedVid;
end
    
if ch==11 % jpeg compression
    for j=1:NumFrames
        I=EncryptedVid(:,:,:,j);
        imwrite(I,'jpgfile.jpg')
        I2=imread('jpgfile.jpg');
        EncryptedVid2(:,:,:,j)=I2;
    end       
    I3=EncryptedVid2(:,:,:,i);    
    reconstructedCover=I3;
     if mode==1
        Wimg=extraction2(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    elseif mode==2
        Wimg=extraction(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    end        
end

if ch==5 % cropping
    I=EncryptedVid(:,:,:,i);   
    figure, imshow(I)
    reconstructedCover=imcrop;
    EncryptedVid2=EncryptedVid;
     if mode==1
        Wimg=extraction2(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    elseif mode==2
        Wimg=extraction(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    end        
end    

if ch==10 % frame averaging
    sumI=zeros(size(EncryptedVid(:,:,:,1)));
    sumI=uint8(sumI);
    for j=1:NumFrames
        I=EncryptedVid(:,:,:,j);
        sumI=imadd(sumI,I);
    end
    
    reconstructedCover=sumI./NumFrames;
     if mode==1
        Wimg=extraction2(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    elseif mode==2
        Wimg=extraction(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    end        
    EncryptedVid2=reconstructedCover;
end
    
if ch==8 % frame dropping
    framestodrop=10;
    vec=randi(NumFrames,1,framestodrop);
    EncryptedVid2=EncryptedVid;
    EncryptedVid2(:,:,:,vec)=[];
    
    reconstructedCover=EncryptedVid2(:,:,:,i);
     if mode==1
        Wimg=extraction2(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    elseif mode==2
        Wimg=extraction(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    end        
end

if ch==9 % frame swapping
    vec=randi(NumFrames,1,NumFrames);
    EncryptedVid2=EncryptedVid(:,:,:,vec);
    sub1=sub1(:,:,vec);
    
    reconstructedCover=EncryptedVid2(:,:,:,i);
     if mode==1
        Wimg=extraction2(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    elseif mode==2
        Wimg=extraction(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1);    
    end        
end

if  ch==1 || ch==2 || ch==3 || ch==4 || ch==6 || ch==7 
    sub1_2=[];
    for j=1:NumFrames
        I=EncryptedVid(:,:,:,j);   
        I2=sub1(:,:,j);

        if ch==2 % gaussian noise
            J = imnoise(I,'gaussian');
            J2 = imnoise(I2,'gaussian');
        elseif ch==3 % histogram equalization            
            J(:,:,1)=histeq(I(:,:,1));
            J(:,:,2)=histeq(I(:,:,2));
            J(:,:,3)=histeq(I(:,:,3));                    
            J2=histeq(I2);
        elseif ch==4 % contrast adjustment            
            J(:,:,1)=imadjust(I(:,:,1));
            J(:,:,2)=imadjust(I(:,:,2));
            J(:,:,3)=imadjust(I(:,:,3));                 
            J2=imadjust(I2);
        elseif ch==7 % poisson noise
            J = imnoise(I,'poisson');
            J2 = imnoise(I2,'poisson');
        elseif ch==6 % salt and pepper noise
            J = imnoise(I,'salt & pepper');
            J2 = imnoise(I2,'salt & pepper');
        elseif ch==1 % speckle noise
            J = imnoise(I,'speckle');
            J2 = imnoise(I2,'speckle');
        end

        EncryptedVid2(:,:,:,j)=J;
        sub1_2(:,:,j)=J2;
%         figure(1), imshow(EncryptedVid2(:,:,:,j))
%         pause
    end

    reconstructedCover=EncryptedVid2(:,:,:,i);        
     if mode==1
        Wimg=extraction2(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1_2);    
    elseif mode==2
        Wimg=extraction(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1_2);    
    end        
end

% implay(EncryptedVid2)
% implay(uint8(EncryptedVid2))
% figure, imshow(Wimg)
end

Code 11 – Function M File – ExtractionProcedure.m

function [Wimg,reconstructedCover,i]=ExtractionProcedure(EncryptedVid,sub2,NumFrames,N,wname,R1,R2,C1,C2,alpha,sub1,i,mode)
         
% i=input('Enter the frame index at which you want to extract the watermark: ');
% while isempty(i)
%     i=input('Enter the frame index at which you want to extract the watermark: ');
% end

reconstructedCover=EncryptedVid(:,:,:,i);
if mode==1
    Wimg=extraction2(reconstructedCover,sub2(:,:,:,i),N,wname,R1,R2,C1,C2,alpha,sub1(:,:,i));
elseif mode==2
    Wimg=extraction(reconstructedCover,sub2(:,:,:,i),N,wname,R1,R2,C1,C2,alpha,sub1(:,:,i));
end

end

Code 12 – Function M File – extraction2.m

function Wimg=extraction2(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1)

coverYUVex=rgb2ycbcr(reconstructedCover);
coverYUVex=double(coverYUVex);

Yframeex=coverYUVex(:,:,1);
Uframeex=coverYUVex(:,:,2);
Vframeex=coverYUVex(:,:,3);

[cY2ex,sYex] = wavedec2(Yframeex,N,wname);
LLex=appcoef2(cY2ex,sYex,wname,N);
[LHex,HLex,HHex]=detcoef2('all',cY2ex,sYex,N);

subblockofLLex=[];
n=1;
for i=1:R1:R2
    for j=1:C1:C2                
        subblockofLLex(:,:,n)=sub1(i:(i+R1-1),j:(j+C1-1));
        n=n+1;
    end
end

[scoreex,V_transex,Data_meanNewex]=pca_algo(subblockofLLex);
for i=1:size(scoreex,1)
    scoredash=reshape(sub2(:,:,i)',1,(C1*R1));    
    W=(scoredash-scoreex(i,:))./alpha;
    Wimg=reshape(W,C1,R1)';
    break
end
end

Code 13 – Function M File – extraction.m

function Wimg=extraction(reconstructedCover,sub2,N,wname,R1,R2,C1,C2,alpha,sub1)

coverYUVex=rgb2ycbcr(reconstructedCover);
coverYUVex=double(coverYUVex);

Yframeex=coverYUVex(:,:,1);
Uframeex=coverYUVex(:,:,2);
Vframeex=coverYUVex(:,:,3);

[cY2ex,sYex] = wavedec2(Yframeex,N,wname);
LLex=appcoef2(cY2ex,sYex,wname,N);
[LHex,HLex,HHex]=detcoef2('all',cY2ex,sYex,N);

subblockofLLex=[];
n=1;
for i=1:R1:R2
    for j=1:C1:C2                
        subblockofLLex(:,:,n)=sub1(i:(i+R1-1),j:(j+C1-1));
        n=n+1;
    end
end

[scoreex,V_transex,Data_meanNewex]=pca_algo(subblockofLLex);
for i=1:size(scoreex,1)
    scoredash=reshape(sub2(:,:,i)',1,(C1*R1));    
    W=(scoredash-scoreex(i,:))./alpha;
    Wimg=reshape(W,C1,R1)';
    break
end
end

 

Recent Posts

Tags

ad-hoc networks AODV boundary detection process classification clustering clustering algorithm Colour Information computer vision Decryption Encryption EZRP ICM (Iterated Conditional Modes) image denoising image enhancement IMAGE PROCESSING image segmentation Imaging and image processing MANET Markov Random Fields neutrosophic logic optical network proposed method PSNR QLab system region growing Robert’s operator Seed point selection segmentation semi-automatic algorithm Shadow Detection shadow removal wall motion wireless communication Wireless network wireless networks Wireless Sensor Network wireless sensor networks ZRP