Samia Souror

Samia Souror

  • NA
  • 33
  • 5.1k

How to pick the corresponding value of the key in the Dictio

Apr 28 2019 9:18 AM
I have a program that encrypt every one plain text character to two cipher text characters, so I want to use a dictionary to store every plain text character and its corresponding cipher text characters, and check if the key and its value already exist in the dictionary then pick its value and add to the next positions for the final encrypted bytes instead of encrypting it again(to minimize the time of encrypting the same character )as shown in the following code
public String Encrypt(String PlainText, String Key)
{
Dictionary<int, byte[]> PlainToCipherDic = new Dictionary<int, byte[]>();
String EncryptedText = "";
Byte[] KeyHashBytes = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(Key));
..some code.....
Byte[] LeftHash = Encoding.ASCII.GetBytes(KeyHashChunks[0]);
Byte[] RightHash = Encoding.ASCII.GetBytes(KeyHashChunks[1]);
Byte[] PlainBytes = Encoding.ASCII.GetBytes(PlainText);
Byte[] Mapping = new Byte[PlainBytes.Length];
Byte[] EncryptedBytes = new Byte[PlainBytes.Length * 2];
byte[] ReturnedEncryptedValue = new byte[PlainBytes.Length];
for (int i = 0; i < PlainBytes.Length; i++)
{
int XoredInt = Convert.ToInt32(PlainBytes[i]);
if (!PlainToCipherDic.ContainsKey(XoredInt))
{
int PlainInteger = XoredInt;
bool Left = (PlainInteger % 2 == 0);
int MappingIndex = (PlainInteger % 16);
PlainBytes[i] = (byte)((Left) ? (PlainBytes[i] ^ LeftHash[MappingIndex]) : (PlainBytes[i] ^ RightHash[MappingIndex]));
int PlainByteInteger = (int)PlainBytes[i];
PlainBytes[i] = (byte)(Math.Floor(((double)(PlainByteInteger) / 2)) + 33);
Mapping[i] = (byte)(MappingIndex + ((Left) ? 0 : 16));
Mapping[i] = (byte)((((PlainByteInteger) % 2 == 1)) ? ((int)Mapping[i]) + 32 : ((int)Mapping[i]) + 0);
Mapping[i] = (byte)(((int)Mapping[i]) + 33);
EncryptedBytes[i * 2] = PlainBytes[i];
EncryptedBytes[i * 2 + 1] = Mapping[i];
PlainToCipherDic.Add(XoredInt, EncryptedBytes);
}
else
{
EncryptedBytes = PlainToCipherDic[XoredInt];
}
}
EncryptedText = Encoding.ASCII.GetString(EncryptedBytes);
Console.WriteLine("EncryptedText : " + EncryptedText);
return EncryptedText;
}
But, at the case of founding the key in the dictionary , the value of the key cannot retrieved from the dictionary and added to the next position of the final encrypted bytes.

Answers (4)