/* * Transforms a pair of characters based on the rules of the playfair cipher. * The direction argument represents wether the pair is being encrypted or decrypted. */ private StringBuilder TransformCharacterPair(char x, char y, int direction) { StringBuilder sb = new StringBuilder(); int xColumnValue = MyPolybiusSquare.GetColumnValueOf(x), xLineValue = MyPolybiusSquare.GetLineValueOf(x), yColumnValue = MyPolybiusSquare.GetColumnValueOf(y), yLineValue = MyPolybiusSquare.GetLineValueOf(y); if (xColumnValue == yColumnValue) { int xEncryptedVal = WrapLineValue(xLineValue + direction, direction) * 10 + xColumnValue; int yEncryptedVal = WrapLineValue(yLineValue + direction, direction) * 10 + yColumnValue; sb.Append(MyPolybiusSquare.GetElementOfValue(xEncryptedVal)); sb.Append(MyPolybiusSquare.GetElementOfValue(yEncryptedVal)); } else if (xLineValue == yLineValue) { int xEncryptedVal = xLineValue * 10 + WrapColumnValue(xColumnValue + direction, direction); int yEncryptedVal = yLineValue * 10 + WrapColumnValue(yColumnValue + direction, direction); sb.Append(MyPolybiusSquare.GetElementOfValue(xEncryptedVal)); sb.Append(MyPolybiusSquare.GetElementOfValue(yEncryptedVal)); } else { int xEncryptedVal = yLineValue * 10 + xColumnValue; int yEncryptedVal = xLineValue * 10 + yColumnValue; sb.Append(MyPolybiusSquare.GetElementOfValue(xEncryptedVal)); sb.Append(MyPolybiusSquare.GetElementOfValue(yEncryptedVal)); } return(sb); }
public override String Encrypt(String text) { StringBuilder sb = new StringBuilder(), firstHalf = new StringBuilder(), secondHalf = new StringBuilder(); for (int i = 0; i < text.Length; i++) { firstHalf.Append(MyPolybiusSquare.GetLineValueOf(text[i])); secondHalf.Append(MyPolybiusSquare.GetColumnValueOf(text[i])); } String polybiusNumbers = firstHalf.Append(secondHalf).ToString(); for (int i = 0; i < polybiusNumbers.Length / 2; i++) { int.TryParse(polybiusNumbers.Substring(i * 2, 2), out int value); sb.Append(MyPolybiusSquare.GetElementOfValue(value)); } return(sb.ToString()); }
/* * It splits the text into 2 digit numbers, and from each one the value of the current encryption character will be deducted. */ public override String Decrypt(String text) { StringBuilder sb = new StringBuilder(); String[] numbers = text.Split(' '); int progress = 0; for (int i = 0; i < numbers.Length; i++) { int.TryParse(numbers[i], out int currentNumber); char currentEncryptionKeyChar = Key.StringValue[progress % Key.StringValue.Length]; sb.Append(MyPolybiusSquare.GetElementOfValue(currentNumber - MyPolybiusSquare.GetValueOf(currentEncryptionKeyChar))); progress++; } return(sb.ToString()); }