function playfair
K = ['YANURY';'XZWSPX';'EDCFVE';'TGBHJT';'MIKOLM';'YANUR '];
ulang = 'Y';
while (upper(ulang) == 'Y')
clc;
display('PLAYFAIR CIPHER');
display(' ');
display('Kunci:');
disp(K);
display(' ');
display('Mode:');
display('1. Encrypt');
display('2. Decrypt');
display('3. Ubah Kunci');
display(' ');
mode = input('Masukkan pilihan: ');
switch mode
case 1
T = input('Plaintext: ','s');
[P C] = encrypt(T,K);
display(['Plaintext (encoded): ' cetak2(P)]);
display(['Ciphertext: ' cetak2(C)]);
display(' ');
case 2
T = input('Ciphertext: ','s');
[P C S] = decrypt(T,K);
display(['Ciphertext: ' cetak2(C)]);
display(['Plaintext (encoded): ' cetak2(P)]);
display(['Suggestion: ' S]);
display(' ');
case 3
display('Masukkan kalimat untuk mengenerate kunci');
display('(kosongkan untuk kunci acak)');
T = input('Kunci: ','s');
K = changekey(T);
display(' ');
display('Kunci yang digunakan: ');
disp(K);
display(' ');
otherwise
disp('Unknown input/mode');
display(' ');
end
ulang = input('Tekan y/Y untung mengulang: ','s');
end
function [P C] = encrypt(P,K)
% Ubah Q menjadi X
l1 = 1;
l2 = 0;
while(l1 ~= l2)
l1 = length(P);
P = regexprep(P, '(.)\1', '$1Z$1'); % Menyisipkan x diantara 2 huruf yg sama
l2 = length(P);
end
P = upper(P);
l = length(P);
C = char(zeros(1,l));
function [P C S] = decrypt(C,K)
if mod(length(C),2) == 1
error('Input bukan ciphertext hasil playfair cipher!!!');
end
l = length(C);
P = char(zeros(1,l));
if c1-1 == 0
c1 = 6;
end
if c2-1 == 0
c2 = 6;
end
P(i:i+1) = [K(r1,c1-1) K(r2,c2-1)];
elseif c1 == c2
if r1-1 == 0
r1 = 6;
end
if r2-1 == 0
r2 = 6;
end
P(i:i+1) = [K(r1-1,c1) K(r2-1,c2)];
else
% Suggestion Algorithm
% Ubah X yg ada di antara 2 huruf jadi x untuk suggestion
S = P;
l1 = 1;
l2 = 0;
while(l1 ~= l2)
l1 = length(S);
S = regexprep(S, '(?<any>.)Z\k<any>', '$<any>Z$<any>');
l2 = length(S);
end
S = upper(regexprep(S, 'Z', ''));
l = length(S);
if S(l) == 'Z'
S(l) = '';
end
function K = changekey(str)
K = char(zeros(1,25));
if isempty(str)
K = randperm(25);
c = find(K == ('Q'-'A'));
% Hilangkan Q
K(c) = 26;
K = char(K+'A'-1);
else
j = 1;
for i=1:length(str)
if isempty(find(K == str(i), 1))
K(j) = str(i);
j = j+1;
end
end
for i=0:25
if char(i+'A') ~= 'Q'
if isempty(find(K == char(i+'A'), 1))
K(j) = char(i+'A');
j = j+1;
end
end
end
end
K = reshape(K, [5 5])';
col = K(:,1);
row = K(1,:);
K =[K col;row ' '];
l = length(str);
str1 = char(zeros(1));
j = 1;
for i=1:2:l
str1(j:j+2) = [str(i) str(i+1) ' '];
j = j+3;
end
n = length(str1);
str1(n) = '';