
load('WS3.mat');

samples = 1000;

analyzed_traces = 'traces_noDummy';
%analyzed_traces = 'traces_withDummy';

byte_to_attack = 1;

delta = 9441-6729;

more off

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Prepare plaintexts
D = aes_plaintexts(1:samples, byte_to_attack);
clear aes_plaintexts byte_to_attack

% Prepare traces
eval(sprintf('traces = %s(1:samples, :);', analyzed_traces));
clear analyzed_traces

K = uint8(0:255);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% TASK 2
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Calculate hypothetical intermediate values
V = SubBytes(bitxor(repmat(D, 1, length(K)), repmat(K, samples, 1)) + 1);

% Calculate hypothetical power consumption
H = HW(V+1);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Calculate correlation
tr_length = size(traces, 2);
R = zeros(length(K), tr_length);

for key_idx = uint16(K)+1
    fprintf('Working on key guess = %d\n', K(key_idx));
    
    for k = 1:tr_length
        r = corrcoef( [double(H(:,key_idx)) double(traces(:,k))] );
        R(key_idx, k) = r(1, 2);
    end
end
clear key_idx k r

% Plot correlation traces
%show_plots(R, 1, 256, 4)
%octave_plot2(R, 1, 256, 2, 2)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% TASK 6
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Preprocess traces with windowing
traces_pre = int16(traces(:, 1:end-delta)) + int16(traces(:, 1+delta:end));

% Calculate correlation with preprocessed traces
tr_length = size(traces, 2);
R_win = zeros(length(K), tr_length-delta);

for key_idx = uint16(K)+1
    fprintf('Working on key guess = %d\n', K(key_idx));
    
    for k = 1:tr_length-delta
        r = corrcoef( [double(H(:,key_idx)) double(traces_pre(:,k))] );
        R_win(key_idx, k) = r(1, 2);
    end
end
clear key_idx k r

% Plot correlation traces
%show_plots(R_win, 1, 256, 4)
%octave_plot2(R_win, 1, 256, 2, 2)
