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