[英]Using Dictionary to map byte to BitArray
我正在開發實現簡單替換密碼的應用程序。 現在出於速度原因(並且這是其中的條件之一),我需要使用BitArray進行加密和解密。 用戶將輸入“編碼”字母,而我需要以某種方式進行映射,因此我選擇了Dictionary,因為它使用哈希表並且在用戶訪問數據時具有O(1)復雜性。 但是現在我發現自己想知道當我像這樣初始化“編碼”字母時該怎么做:
BitArray codedAlphabet = new BitArray(bytes);
這將使我使用2 for循環來實現我的目標。 有人有不同的想法嗎? 希望您理解我正在努力實現的目標。 先感謝您。
碼:
namespace Harpokrat.EncryptionAlgorithms
{
// Simple substitution cypher algorithm
public class SimpleSubstitutionStrategy : IEncryptionStrategy
{
private string alphabet; // message to be encrypted
private string coded; // this will be the key (input from file or from UI)
private ArrayList AlphabetBackUp = new ArrayList();
private ArrayList CodedBackUp = new ArrayList();
#region Properties
public string Alphabet
{
get
{
return this.alphabet;
}
set
{
this.alphabet = value;
foreach (char c in this.alphabet.ToCharArray())
{
this.AlphabetBackUp.Add(c);
}
}
}
public string Coded
{
get
{
return this.coded;
}
set
{
this.coded = "yqmnnsgwatkgetwtawuiqwemsg"; //for testing purposes
foreach (char c in this.coded.ToCharArray())
{
this.CodedBackUp.Add(c);
}
}
}
#endregion
public string Decrypt(string message)
{
message = message.ToLower();
string result = "";
for (int i = 0; i < message.Length; i++)
{
int indexOfSourceChar = CodedBackUp.IndexOf(message[i]);
if (indexOfSourceChar < 0 || (indexOfSourceChar > alphabet.Length - 1))
{
result += "#";
}
else
{
result += alphabet[indexOfSourceChar].ToString();
}
}
return result;
}
public string Encrypt(string message)
{
message = message.ToLower();
string result = "";
for(int i = 0; i < message.Length; i++)
{
int indexOfSourceChar = AlphabetBackUp.IndexOf(message[i]);
if (indexOfSourceChar < 0 || (indexOfSourceChar > coded.Length - 1))
{
result += "#";
}
else
{
result += coded[indexOfSourceChar].ToString();
}
}
return result;
}
}
}
我建議同時使用一種方法來設置alphabet
和coded
,該方法在內部構建您需要執行加密和解密操作的兩個字典,以及一種用於執行get-or-return-default('# (以您的情況為准)。 這樣,您可以實現一個函數,該函數根據傳入的字典進行加密或解密(如果您願意使用LINQ,可以在一行代碼中實現)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.