Link to home
Start Free TrialLog in
Avatar of tommym121
tommym121Flag for Canada

asked on

C# - How to encrypt a data dictionary

I have a class that read a delimited file with a string and a integer and store it into a data dictionary.

I will like to encrypt it into a file and later be able to read the encrypt file and put data back into the data dictioanry.  

I have the code below and not sure where I need to add to encrypt the data.  
I thought I will write data dictionary into a memory file and then write using cryptostream. Is that correct?  If I do this how can I retrieve it and restore the key/value into the data dictionary
Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

A simple way would be convert the dictionary to string by having 2 different delimiters inside.
One between key and its value and another between each key-value pair.
Example:
key1@value1|key2@value2|key3@value3

To convert dictionary to such representation:
String.Join("|", dictionary.Select(kv=>String.Format("{0}@{1}",kv.Key,kv.Value).ToArray());
U must choose delimiters that u know are not part of the dictionary keys or values otherwise u wont get the conversion right.
Next step is to encrypt the string.
To get dictionary back from the string:
var dictionary = str.Split('|').ToDictionary(s=>s.Split('@')[0],s=>s.Split('@')[1]);
Avatar of tommym121

ASKER

I have created the encrypt file with the routine below. How would I read it back.
Do I first read all the bytes from CryptoStream. Then put into the memorystream, then read from memory stream and restore data into the dictionary.  Any help will appreciated

        public void EncryptAndSerialize(string filename, SymmetricAlgorithm key)
        {
            using (FileStream fs = File.Open(filename, FileMode.Create))
            {
                using (CryptoStream cs = new CryptoStream(fs, key.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        foreach (var item in map)
                        {

                            string line = item.Key + "," + item.Value + "\n";
                            byte[] array = Encoding.ASCII.GetBytes(line);
                            ms.Write(array, 0, line.Length);
                        }
                        byte[] allbytes = ms.GetBuffer();
                        cs.Write(allbytes, 0, allbytes.Length);
                    }

                }
            }
        }
ASKER CERTIFIED SOLUTION
Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks