|
| 1 | +using System; |
| 2 | +using System.Globalization; |
| 3 | +using System.Text; |
| 4 | +using System.Text.RegularExpressions; |
| 5 | + |
| 6 | +namespace Algorithms.Encoders |
| 7 | +{ |
| 8 | + /// <summary> |
| 9 | + /// Class for AutoKey encoding strings. |
| 10 | + /// </summary> |
| 11 | + public class AutokeyEncorder |
| 12 | + { |
| 13 | + /// <summary> |
| 14 | + /// Autokey Cipher is a type of polyalphabetic cipher. |
| 15 | + /// This works by choosing a key (a word or short phrase), |
| 16 | + /// then you append the plaintext to itself to form a longer key. |
| 17 | + /// </summary> |
| 18 | + /// <param name="plainText">The string to be appended to the key.</param> |
| 19 | + /// <param name="keyword">The string to be appended to the plaintext.</param> |
| 20 | + /// <returns>The Autokey encoded string (All Uppercase).</returns> |
| 21 | + public string Encode(string plainText, string keyword) |
| 22 | + { |
| 23 | + plainText = Regex.Replace(plainText.ToUpper(CultureInfo.InvariantCulture), "[^A-Z]", string.Empty); |
| 24 | + keyword = keyword.ToUpper(CultureInfo.InvariantCulture); |
| 25 | + |
| 26 | + keyword += plainText; |
| 27 | + |
| 28 | + StringBuilder cipherText = new StringBuilder(); |
| 29 | + |
| 30 | + for(int i = 0; i < plainText.Length; i++) |
| 31 | + { |
| 32 | + char plainCharacter = plainText[i]; |
| 33 | + char keyCharacter = keyword[i]; |
| 34 | + |
| 35 | + int encryptedCharacter = (plainCharacter - 'A' + keyCharacter - 'A') % 26 + 'A'; |
| 36 | + cipherText.Append((char)encryptedCharacter); |
| 37 | + } |
| 38 | + |
| 39 | + return cipherText.ToString(); |
| 40 | + } |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// Removed the key from the encoded string. |
| 44 | + /// </summary> |
| 45 | + /// <param name="cipherText">The encoded string.</param> |
| 46 | + /// <param name="keyword">The key to be removed from the encoded string.</param> |
| 47 | + /// <returns>The plaintext (All Uppercase).</returns> |
| 48 | + public string Decode(string cipherText, string keyword) |
| 49 | + { |
| 50 | + cipherText = Regex.Replace(cipherText.ToUpper(CultureInfo.InvariantCulture), "[^A-Z]", string.Empty); |
| 51 | + keyword = keyword.ToUpper(CultureInfo.InvariantCulture); |
| 52 | + |
| 53 | + StringBuilder plainText = new StringBuilder(); |
| 54 | + StringBuilder extendedKeyword = new StringBuilder(keyword); |
| 55 | + |
| 56 | + for(int i = 0; i < cipherText.Length; i++) |
| 57 | + { |
| 58 | + char cipherCharacter = cipherText[i]; |
| 59 | + char keywordCharacter = extendedKeyword[i]; |
| 60 | + |
| 61 | + int decryptedCharacter = (cipherCharacter - 'A' - (keywordCharacter - 'A') + 26) % 26 + 'A'; |
| 62 | + plainText.Append((char)decryptedCharacter); |
| 63 | + extendedKeyword.Append((char)decryptedCharacter); |
| 64 | + } |
| 65 | + |
| 66 | + return plainText.ToString(); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments