c#, encrypt and decrypt

In the last post I worried about having an online database of email addresses.  Is there a way to encrypt such data while stored in the database?  Of course there is if you have an enterprise version of sql server and you have full control over the database instance. I mention this because in the project I have in mind I do not have complete admin control of the database so some settings I cannot set. Also the version that is most cost effective is the free ‘express edition’ of sQL Server for which some functions are not present.

So after some digging around I decided to merely create c# classes to demo the use of encryption and decryption in case we do decided to encrypt the email addresses. I want to mention that even though the requirements don’t call for encrypting the data, one should start thinking early about security considerations.

Also, I learned the initialization vector is important. You need to create one properly and remember it in order to decrypt the data later. You also need to remember the key (of course). In the dot net classes there are methods to generate a key and the initialization vector (IV) but if you wanted to you can come up with your own values. In the demo class, I make sure to set a property with those values so when I  decrypt I can reference them. In this particular demo, the values are generated dynamically so you don’t have think up one. However if you plan to store an encrypted value in the database, you will have to come up with some kind of key management method.

And now, here are the classes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CryptoHelper
{
    public class DecryptTool
    {
        private byte[] _initializationVector;
        private byte[] _key;
        public byte[] initializationVector { get { return _initializationVector; } set { _initializationVector = value; } }
        public byte[] key { get { return _key; } set { _key = value; } }
        private string _PlainText;

        public string PlainText { get { return _PlainText; } set {_PlainText=value;} }

        public DecryptTool(byte[] encrypted, byte[] key, byte[] initializationVector)
        {
            using (System.Security.Cryptography.AesCryptoServiceProvider aesp = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
                aesp.Key = key;
                aesp.IV = initializationVector;

                // Create a decrytor to perform the stream transform.
                System.Security.Cryptography.ICryptoTransform decryptor = aesp.CreateDecryptor(key, initializationVector);

                // Create the streams used for decryption. 
                using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(encrypted))
                {
                    using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                    {
                        using (System.IO.StreamReader srDecrypt = new System.IO.StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream 
                            // and place them in a string.
                            PlainText = srDecrypt.ReadToEnd();
                        }
                    }
                }

            }

            

        }
    }
    public class EncryptTool
    {
        private byte[] _initializationVector;
        private byte[] _key;
        public byte[] initializationVector { get { return _initializationVector; } set { _initializationVector = value; } }
        public byte[] key { get { return _key; } set { _key = value; } }
        public byte[] encrypted;
        public EncryptTool(string plaintext)
        {
            
            using (System.Security.Cryptography.AesCryptoServiceProvider aesp = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
            aesp.GenerateIV();
            aesp.GenerateKey();
            key = aesp.Key;
            initializationVector = aesp.IV;

            // Create a decrytor to perform the stream transform.
            System.Security.Cryptography.ICryptoTransform encryptor = aesp.CreateEncryptor(aesp.Key, aesp.IV);

            using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
            {
                using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    using (System.IO.StreamWriter swEncrypt = new System.IO.StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plaintext);
                    }

                    encrypted = msEncrypt.ToArray();
                }

            }

            }

        }

    }
}

The console program to test the class is here:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestEncryption
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("encryption demo");
            string myPlainText = "hello, this is the encryption demo.";
            Console.WriteLine("the plaintext:'{0}'", myPlainText);
            CryptoHelper.EncryptTool e = new CryptoHelper.EncryptTool(myPlainText);
            Console.WriteLine(Convert.ToBase64String(e.encrypted));
            CryptoHelper.DecryptTool d = new CryptoHelper.DecryptTool(e.encrypted,e.key,e.initializationVector);
            Console.WriteLine("decryped:{0}", d.PlainText);
            Console.WriteLine("Press any key");
            Console.Read();

        }
    }
}

Now here is a sample output from the program:

encryption_demo

encryption_demo

 

 

Posted in C#