Category Archives: C#

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.

The console program to test the class is here:

 

Now here is a sample output from the program:

encryption_demo

encryption_demo