Click here to Skip to main content
Click here to Skip to main content

Encrypt and Decrypt Data with C#

, 18 May 2006
Rate this:
Please Sign up or sign in to vote.
Encrypt and decrypt important data with C# and play


Well most of the beginner and intermediate programmers like to play with cryptography. This is the part that took me to some trouble in my life. A good encryption and decryption code is easily findable in the Internet and even on The Code Project. Why another? I didn't find a suitable reason behind that one. And when I found some, I mixed them up and this is the result. I just wanted to share the result.

The Solution

solution Image - solution.jpg

I included a tiny demo solution with an implementation of the segment. Hope it helps you. As you see from the snapshot, the CryptorEngine class holds the two static methods, encryption and decryption. The reason I put them to a separate file was because it is the best practice as far as I know and most importantly, other blocks can access these methods easily.

The Encryption

encrypt Image - encrypt.jpg

The encrypt method goes like this. I need to say something about the cipherMode of the tripleDES cryptographic service provider. We used the ECB (Electronic Code Book). The ECB mode encrypts each block individually. This means that any block of the plain text that are identical and in the same message or even in a different message but encrypted with the same key, will be transformed into identical cipher text blocks. If the plain text to be encrypted contains substantial repetition, it is feasible for the cipher text to be broken one block at a time. Also it is possible for an active adversary to substitute and exchange individual blocks without detection. If a single bit of the cipher text block is mangled, the entire corresponding plain text block will be mangled.

public static string Encrypt(string toEncrypt, bool useHashing)
    byte[] keyArray;
    byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

    System.Configuration.AppSettingsReader settingsReader = 
                                        new AppSettingsReader();
    // Get the key from config file

    string key = (string)settingsReader.GetValue("SecurityKey", 
    //If hashing use get hashcode regards to your key
    if (useHashing)
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        //Always release the resources and flush data
        // of the Cryptographic service provide. Best Practice

        keyArray = UTF8Encoding.UTF8.GetBytes(key);

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    //set the secret key for the tripleDES algorithm
    tdes.Key = keyArray;
    //mode of operation. there are other 4 modes.
    //We choose ECB(Electronic code Book)
    tdes.Mode = CipherMode.ECB;
    //padding mode(if any extra byte added)

    tdes.Padding = PaddingMode.PKCS7;

    ICryptoTransform cTransform = tdes.CreateEncryptor();
    //transform the specified region of bytes array to resultArray
    byte[] resultArray = 
      cTransform.TransformFinalBlock(toEncryptArray, 0, 
    //Release resources held by TripleDes Encryptor
    //Return the encrypted data into unreadable string format
    return Convert.ToBase64String(resultArray, 0, resultArray.Length);


decrypt Image - decrypt.jpg

Well, as you can see, the decryption method is just kind of opposite of the encryption. I talked about the Cipher Mode ECB in the encrypt section. Now let's talk about the padding mode PKCS7. Padding comes when a message data block is shorter than full number of bytes needed for a cryptographic operation. Why did we choose PCKS7. This is because PCKS#7 padding string consists of a sequence of bytes, each of which equal the total number of padding bytes added.

public static string Decrypt(string cipherString, bool useHashing)
    byte[] keyArray;
    //get the byte code of the string

    byte[] toEncryptArray = Convert.FromBase64String(cipherString);

    System.Configuration.AppSettingsReader settingsReader = 
                                        new AppSettingsReader();
    //Get your key from config file to open the lock!
    string key = (string)settingsReader.GetValue("SecurityKey", 
    if (useHashing)
        //if hashing was used get the hash code with regards to your key
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        //release any resource held by the MD5CryptoServiceProvider

        //if hashing was not implemented get the byte code of the key
        keyArray = UTF8Encoding.UTF8.GetBytes(key);

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    //set the secret key for the tripleDES algorithm
    tdes.Key = keyArray;
    //mode of operation. there are other 4 modes. 
    //We choose ECB(Electronic code Book)

    tdes.Mode = CipherMode.ECB;
    //padding mode(if any extra byte added)
    tdes.Padding = PaddingMode.PKCS7;

    ICryptoTransform cTransform = tdes.CreateDecryptor();
    byte[] resultArray = cTransform.TransformFinalBlock(
                         toEncryptArray, 0, toEncryptArray.Length);
    //Release resources held by TripleDes Encryptor                
    //return the Clear decrypted TEXT
    return UTF8Encoding.UTF8.GetString(resultArray);

Web.Config/App.Config file. Why?

You want to change your key. But you are not the developer? Or you do not even have the source! Then what? Thanks to the Web.config/app.config file idea. Keep your secret key in the config file. Change it when you need to.

<?xml version="1.0" encoding="utf-8" ?>

How to Use

To use the code sample, you can copy the CryptorEngine to your project and start playing or copy method bodies and paste to your application projects.

To Do

You can try to encrypt the key and save it (encrypted) to config file for an extra bit of security.


This code works fine with .NET 1.1. I built the project in Visual Studio 2005 because some methods expired in .NET 2.0 and changed. For example, the configuration namespace changed a lot. So I built the example in Visual Studio 2005 to see if it works on v2.0 too. And it works with ZERO change and ZERO error.


  • 18th May, 2006: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Syed Moshiur Murshed
Software Developer Pöyry Infra GmbH
Austria Austria
I am Syed Moshiur Murshed from Bangladesh. I studied BSC in Computer Science at American International University Bangladesh( And then MSC in Software Technology at Stuttgart University of Applied Science, Germany( Currently I am employed as a Software Engineer at Pöyry Infra GmbH in Salzburg, Austria since 04-2011.
I have been learning C# for quite some time and Enjoying it.

Comments and Discussions

GeneralEncrypt and Decrypt Data with C# PinmemberMember 107740694-May-14 20:32 
GeneralMy vote of 5 PinpremiumPaulo Augusto Künzel2-Apr-14 3:26 
GeneralMy vote of 5 Pinmembercsharpbd29-Jan-14 0:21 
Questiondoes it have a testcase already? how to create unit test for this project ? what codes am i going to put? PinmemberMember 1019148623-Sep-13 16:42 
GeneralMy vote of 5 Pinmemberazze2314-Sep-13 6:21 
Suggestionadd SecureString for more security. Pinmemberazze2314-Sep-13 6:21 
GeneralMy vote of 5 PinprofessionalEduardo Antonio Cecilio Fernandes12-Sep-13 16:56 
QuestionThe Key in Base64 - correction Pinmemberousir6-Sep-13 2:07 
GeneralMy vote of 5 Pinmemberbatres-sc24-Aug-13 17:17 
GeneralMy vote of 4 PinprofessionalAmir Mohammad Nasrollahi29-Jul-13 0:33 
Questionlength of the key in bytes PinmemberMember 1003975224-Jul-13 2:56 
QuestionNeed to know whether the below mentioned queries has been answered PinmemberMember 96912264-Jul-13 19:36 
Questiondescrypt fail in case a large text Pinmemberlehongxo11-Jun-13 6:39 
QuestionError with false parameter PinmemberAlessandroZ29-May-13 21:00 
QuestionExcellent Example Pinmemberbhupinder78-May-13 10:23 
QuestionSecurity PinmemberTSoft4-Apr-13 16:48 
AnswerRe: Security PinmemberAlluvialDeposit16-Apr-13 2:10 
GeneralMy vote of 5 PinmemberAttiq-ul-Islam5-Mar-13 0:45 
Questionexcellent example. Pinmemberom das3-Mar-13 22:37 
GeneralPerfect example i was looking for 5 stars PinmemberKlaasjanMors24-Feb-13 1:36 
Questionintroduce using statements PinmemberErikFZR10-Feb-13 23:24 
AnswerRe: introduce using statements PinmemberSyed Moshiur Murshed11-Feb-13 0:50 
QuestionAbout Article Pinmemberkanyogendra24-Dec-12 1:30 
GeneralMy vote of 4 Pinmemberkanyogendra24-Dec-12 1:28 
GeneralMy vote of 5 PinmemberbVagadishnu6-Dec-12 3:44 
QuestionBad Data :CryptographicException was unhandled Pinmemberswati ail26-Oct-12 2:13 
I am getting this error " Bad Data :CryptographicException was unhandled" at the following line
" byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length)"
Before it was working fine but now suddenly it is giving me this error. I am not getting why i am getting this error. Is there any problem with the key or the encrpted code?
AnswerRe: Bad Data :CryptographicException was unhandled Pinmemberbhupinder78-May-13 10:25 
GeneralMy vote of 4 PinmemberSami Ciit1-Oct-12 9:10 
GeneralMy vote of 5 Pinmembercreatives.system15-Aug-12 23:36 
Questiondecryption does not perform correctly. PinmemberAtiq1142-Aug-12 20:13 
QuestionRe: decryption does not perform correctly. PinmemberSyed Moshiur Murshed2-Aug-12 20:19 
GeneralMy vote of 5 Pinmemberclemsy10-Jul-12 4:10 
Questionhi Pinmemberanikccc5-May-12 18:42 
GeneralMy vote of 5 Pinmembermanoj kumar choubey29-Mar-12 20:13 
GeneralMy vote of 5 Pinmembercreatives.idea23-Dec-11 18:47 
GeneralMy vote of 5 PinmemberPrajakta Bhagwat19-Dec-11 19:54 
GeneralMy vote of 5 PinmemberMember 413790128-Oct-11 1:30 
GeneralMy vote of 5 Pinmemberadriancs31-Mar-11 17:47 
GeneralThank you Mürşid PinmemberLevent Uysal4-Mar-11 3:12 
GeneralMy vote of 4 PinmemberTeddy Segoro25-Nov-10 19:05 
GeneralMy vote of 4 Pinmemberbumblez6-Sep-10 14:30 
GeneralMy vote of 4 Pinmemberairfreeze@gmail.com3-Aug-10 21:27 
GeneralThanks PinmemberCoder_91125-Jan-10 23:52 
Questionhow to encrypt /decrypt using C# ECC asymetric algorithm? PinmemberMember 151309928-Oct-09 3:19 
GeneralLibrary Encrypt and Decrypt Methods Using TripleDES and MD5 PinmemberEdy Chandra20-Jan-09 21:48 
Generalc++ version of the decryption Pinmembermonsieur_jj1-Dec-08 21:51 
GeneralDecrpt the password using MD5 PinmemberMember 38073875-Jun-08 23:35 
GeneralRe: Decrpt the password using MD5 PinmemberRohitk7820-Jun-08 0:02 
GeneralRe: Decrpt the password using MD5 PinmemberMember 380738723-Jun-08 18:39 
GeneralRe: Decrpt the password using MD5 Pinmemberitamar8222-Jun-09 22:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140709.1 | Last Updated 18 May 2006
Article Copyright 2006 by Syed Moshiur Murshed
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid