Contents

clear
clc
format long

%Input
keymax = 10;
keymin = 1;
filename = 'ciptext.txt';

%Import poly-alphabetic cipher text and converts to ascii numbers
cip = double(textread(filename,'%c'))-65';
freqenglish = [ 0.08167 	 0.01492 	 0.02782 	 0.04253 	 0.12702 	 0.02228 	 0.02015 	 0.06094 	 0.06966 	 0.00153 	 0.00772 	 0.04025 	 0.02406 	 0.06749 	 0.07507 	 0.01929 	 0.00095 	 0.05987 	 0.06327 	 0.09056 	 0.02758 	 0.00978 	 0.02360 	 0.00150 	 0.01974 	 0.00074 ];

warning('off','MATLAB:xlswrite:AddSheet'); %Supress redundant warning

%Generates split for every possible key length
for i = keymin:keymax
    for k = 1:i
        cipsplit{k,i} = cip(k:i:length(cip))';
    end
end

Finds keyword

for k = keymin:keymax   %Tests in keyword length-direction
    for j = 1:k         %Tests every column in specific length
        for i = 1:26    %Shifts every letter in that column 26 times
            cipsplit{j,k} = mod(cipsplit{j,k}+1,26);
                for r = 1:26
                shape(r,i) = sum(cipsplit{j,k} == r)/length(cipsplit{j,k}); %Compare to english frequency
                end
            dif(i) = sum(abs(shape(:,i)'-freqenglish));                     %Finds total error in all 26 tests
        end
        [~,shift(j,k)] = min(dif);                                           %Extracts index of least error (i.e possible key)
    end

end


%Break text
for k = keymin:keymax

    keyword = shift(:,k)';
    keyword(keyword == 0) = [];
    keyword = char(keyword+64);

    % Just pop-up text
    disp5 = ('Testing best-match keywork of length ' );
    klength = num2str(k);
    messege = [disp5 klength];
    disp(messege)
    disp(' ')
    disp6 = ('Keyword: ');
    disp7 = num2str(keyword);
    messege2 = [disp6 disp7];
    disp(messege2)


    % Serious deciphering going on
    keyword = (double(keyword)-65);

    cipher = double(textread(filename,'%c'))-65';

    for i  = 1:k
        ciph{i} = mod((cipher(i:k:length(cipher))+keyword(i)),26)';
        char(cell2mat(ciph(:,i))+65)';
        xlswrite('plainttext.xlsx',char(cell2mat(ciph(:,i))+65)',k,(char(i+64)))
    end

    clc
end

disp('Congratulations! Your polyalphabetic cipher has been decrypted')
disp(' ')
disp1 = ('An excel spreadsheet named "plaintext" has been genereated. It consists of ');
disp2 = num2str(keymax);
disp3 = ('sheets, each representing a specific keyword length-test.');
disp4 = [disp1 disp2];
disp(disp4)
disp(disp3)
Testing best-match keywork of length 1
  

Congratulations! Your polyalphabetic cipher has been decrypted
 
An excel spreadsheet named "plaintext" has been genereated. It consists of 10
sheets, each representing a specific keyword length-test.