79 lines
2.5 KiB
Text
79 lines
2.5 KiB
Text
class Chaocipher {
|
|
L_ALPHABET : static : Char[];
|
|
R_ALPHABET : static : Char[];
|
|
|
|
function : Main(args : String[]) ~ Nil {
|
|
L_ALPHABET := "HXUCZVAMDSLKPEFJRIGTWOBNYQ"->ToCharArray();
|
|
R_ALPHABET := "PTLNBQDEOYSFAVZKGJRIHWXUMC"->ToCharArray();
|
|
plainText := "WELLDONEISBETTERTHANWELLSAID"->ToCharArray();
|
|
|
|
System.IO.Console->Print("The original plaintext is: ")->PrintLine(plainText);
|
|
"\nThe left and right alphabets after each permutation during encryption are:\n"->PrintLine();
|
|
cipherText := Chao(plainText, Mode->ENCRYPT, true);
|
|
System.IO.Console->Print("\nThe ciphertext is: ")->PrintLine(cipherText);
|
|
plainText2 := Chao(cipherText, Mode->DECRYPT, false);
|
|
System.IO.Console->Print("The recovered plaintext is: ")->PrintLine(plainText2);
|
|
}
|
|
|
|
function : Chao(in : Char[], mode : Mode, show_steps : Bool) ~ Char[] {
|
|
i : Int; j : Int; index : Int;
|
|
store : Char;
|
|
len := in->Size();
|
|
left := Char->New[26]; right := Char->New[26]; temp := Char->New[26];
|
|
eText := Char->New[len];
|
|
|
|
Runtime->Copy(left, 0, L_ALPHABET, 0, L_ALPHABET->Size());
|
|
Runtime->Copy(right, 0, R_ALPHABET, 0, R_ALPHABET->Size());
|
|
|
|
for(i := 0; i < len; i += 1;) {
|
|
if (show_steps) {
|
|
System.IO.Console->Print(left)->Print(' ')->PrintLine(right);
|
|
};
|
|
if (mode = Mode->ENCRYPT) {
|
|
index := IndexOf(right, in[i]);
|
|
eText[i] := left[index];
|
|
}
|
|
else {
|
|
index := IndexOf(left, in[i]);
|
|
eText[i] := right[index];
|
|
};
|
|
|
|
if (i = len - 1) {
|
|
break;
|
|
};
|
|
|
|
# left
|
|
for(j := index; j < 26; j += 1;) { temp[j - index] := left[j]; };
|
|
for(j :=0; j < index; j += 1;) { temp[26 - index + j] := left[j]; };
|
|
store := temp[1];
|
|
for(j := 2; j < 14; j += 1;) { temp[j - 1] := temp[j]; };
|
|
temp[13] := store;
|
|
Runtime->Copy(left, 0, temp, 0, temp->Size());
|
|
|
|
# right
|
|
for(j := index; j < 26; j += 1;) { temp[j - index] := right[j]; };
|
|
for(j :=0; j < index; j += 1;) { temp[26 - index + j] := right[j]; };
|
|
store := temp[0];
|
|
for(j :=1; j < 26; j += 1;) { temp[j - 1] := temp[j]; };
|
|
temp[25] := store;
|
|
store := temp[2];
|
|
for(j := 3; j < 14; j += 1;) { temp[j - 1] := temp[j]; };
|
|
temp[13] := store;
|
|
Runtime->Copy(right, 0, temp, 0, temp->Size());
|
|
};
|
|
|
|
return eText;
|
|
}
|
|
|
|
function : IndexOf(str : Char[], c : Char) ~ Int {
|
|
for(i := 0; i < str->Size(); i += 1;) {
|
|
if(c = str[i]) {
|
|
return i;
|
|
};
|
|
};
|
|
|
|
return -1;
|
|
}
|
|
|
|
enum Mode { ENCRYPT, DECRYPT }
|
|
}
|