I am developing an application that implements Simple Substitution Cypher. Now for speed reasons (and because that was one of the conditions) I need to use BitArray for encryption and decryption. The user will enter "coded" alphabet and I would need to map it in some way so I chose Dictionary since it uses hash table and has O(1) complexity when the user access data. But now I found myself wondering how can I do this when I have "coded" alphabet initialized like this:
BitArray codedAlphabet = new BitArray(bytes);
This would make me use 2 for loops to achieve my goal. Does anyone have different idea? Hopefully you understood what I am trying to achieve. Thank you in advance.
Code:
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;
}
}
}
I'd recommend a single method to set alphabet
and coded
at the same time, that internally builds the two dictionaries you'd need to do Encryption and Decryption, and a helper method to do a get-or-return-default ('#' in your case) on them. That way you can implement a single function that does either Encryption or Decryption depending on the dictionary passed in (which could be implemented in a single line of code if you're comfortable using LINQ).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.