% Framework for developping attacks in Matlab under Windows
% for the DPA contest V2
%
% Version 1, 17/05/2010
%
% Guillaume Duc <guillaume.duc@telecom-paristech.fr>
%

% Execution parameters (TODO)

num_key = 0; % Number of the key to attack in the DB (0..31)
num_traces = 2; % Number of traces to use (1..20000)
result_filename = 'V:\result_k0.dat'; % Name of result file
trace_directory = 'V:\dpa_contest_v2\some_traces\DPA_contest2_public_base_diff_vcc_a128_2009_12_23'; % Name of the directory containing the traces
attack_wrapper = 'V:\Visual Studio 2008\Projects\AttackWrapper\AttackWrapper\bin\Debug\AttackWrapper.exe'; % Path to AttackWrapper.exe

% Attack parameters (TODO)

attacked_subkey = 10; % Number of the attacked subkey (1: subkey used in
% the first round of AES, ..., 10: subkey used in the last roune)


% Load the Wrapper
fprintf('Loading the assembly...\n');
NET.addAssembly(attack_wrapper);

fprintf('Loading the wrapper...\n');
wrapper = AttackWrapper.MatlabWrapper(num_key, num_traces, result_filename, trace_directory, attacked_subkey);

% Init the wrapper
fprintf('Initialization of the wrapper...\n');
wrapper.init();

% Main iteration
for iteration = 1:num_traces
    fprintf('Iteration #%u...\n', iteration);
    trace = wrapper.getTrace;
    result = AttackWrapper.PartialResult(attacked_subkey);
    
    % TODO: put your attack code here
    % Your attack code can use:
    % - trace.plaintext (16 bytes plaintext) :
    %     trace.plaintext(1) ... trace.plaintext(16)
    % - trace.ciphertext (16 bytes ciphertext) :
    %     trace.ciphertext(1)...(16)
    % - trace.samples (3253 int16 samples) :
    %     trace.samples(1)...(3253)
    %
    % And must fill the result.bytes array (16x256) where for each byte of
    % the attacked subkey (the first indice of the array), all the 256
    % possible values of this byte are sorted according to their
    % probability (first position (indice 1): most probable, last (indice
    % 256): least probable), i.e. if your attack is successful, the value
    % of the key is result.bytes(1,1),...,result.bytes(16,1).
    
    % Dummy Example (TODO: replace with your attack)
    for byte_num = 1:16
        for value = 0:255
            result.bytes(byte_num,value+1) = value;
        end
    end
    
    % Send the result to the wrapper
    wrapper.saveResult(result);
end

fprintf('End of the attack\n');

% Close the wrapper
wrapper.endAttack();
