使用字典将字节映射到 BitArray

Using Dictionary to map byte to BitArray

我正在开发一个实现 Simple Substitution Cypher 的应用程序。现在出于速度原因(并且因为这是条件之一)我需要使用 BitArray 进行加密和解密。用户将输入 "coded" 字母表,我需要以某种方式映射它,所以我选择了字典,因为它使用散列 table 并且在用户访问数据时具有 O(1) 复杂度。但是现在我发现自己想知道当我 "coded" 字母初始化如下时我该如何做到这一点:

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;
    }
}
}

我建议使用一种方法同时设置 alphabetcoded,它会在内部构建您需要进行加密和解密的两个词典,以及一个辅助方法对它们执行 get-or-return-default(在你的情况下为“#”)。 这样您就可以实现一个函数,该函数根据传入的字典执行加密或解密(如果您习惯使用 LINQ,可以在一行代码中实现)。