Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#
Article

Encrypt and Decrypt Data with C#

Rate me:
Please Sign up or sign in to vote.
4.82/5 (26 votes)
17 May 2006CPOL3 min read 256K   12.3K   52   25
Encrypt and Decrypt important data with C# and play

Introduction

Well, most 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 found on the Internet and even on The Code Project. Why another? I did not find a suitable reason behind that. And when I found some, I mixed them up and this is the result. I wanted to share the result and hence this article.

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 into a separate file is 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 blocks of plain text that are identical and are 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.

C#
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", typeof(String));
    //System.Windows.Forms.MessageBox.Show(key);
    //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

        hashmd5.Clear();
    }
    else
        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, toEncryptArray.Length);
    //Release resources held by TripleDes Encryptor
    tdes.Clear();
    //Return the encrypted data into unreadable string format
    return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}

Decryption

decrypt Image - decrypt.jpg

Well, as you can see, the decryption method is 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 the full number of bytes needed for a cryptographic operation. Why did we choose PCKS7. Because PCKS#7 padding string consists of a sequence of bytes, each of which is equal to the total number of padding bytes added.

C#
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", typeof(String));

    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

        hashmd5.Clear();
    }
    else
    {
        //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
    tdes.Clear();
    //return the Clear decrypted TEXT
    return UTF8Encoding.UTF8.GetString(resultArray);
}

Web.Config/App.Config file. Why?

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

XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  // The Code Project does not recognize these tags if i put<>.
  // So you Put   <> beside the words
  appSettings>

How to Use

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

To Do

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

Conclusion

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 is 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.

History

  • 18th May, 2006: Initial post

License

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


Written By
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(www.aiub.edu). And then MSC in Software Technology at Stuttgart University of Applied Science, Germany(www.hft-stuttgart.de). 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

 
QuestionNeed fixed length encrypted string output algorithm ? Pin
Manivignesh20-May-14 1:31
Manivignesh20-May-14 1:31 
AnswerRe: Need fixed length encrypted string output algorithm ? Pin
Syed Moshiur Murshed20-May-14 5:05
professionalSyed Moshiur Murshed20-May-14 5:05 
GeneralRe: Need fixed length encrypted string output algorithm ? Pin
Manivignesh20-May-14 19:19
Manivignesh20-May-14 19:19 
QuestionDecrypting the same for duplicate passwords Pin
demouser74321-Jan-13 2:04
demouser74321-Jan-13 2:04 
AnswerRe: Decrypting the same for duplicate passwords Pin
Aron Weiler25-Feb-13 19:55
Aron Weiler25-Feb-13 19:55 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey29-Mar-12 23:28
professionalManoj Kumar Choubey29-Mar-12 23:28 
GeneralThis code is not secure Pin
matthev19-May-09 21:41
matthev19-May-09 21:41 
GeneralRe: This code is not secure Pin
demouser74321-Jan-13 2:02
demouser74321-Jan-13 2:02 
GeneralRe: This code is not secure Pin
Aron Weiler25-Feb-13 19:56
Aron Weiler25-Feb-13 19:56 
Questionwhat magnificent Pin
snopbear1-Feb-09 1:51
snopbear1-Feb-09 1:51 
GeneralError : Invalid length for a Base-64 char array Pin
contact_niraj28-May-08 2:08
contact_niraj28-May-08 2:08 
GeneralRe: Error : Invalid length for a Base-64 char array Pin
geardoom314-Nov-08 5:29
geardoom314-Nov-08 5:29 
GeneralRe: Error : Invalid length for a Base-64 char array Pin
Lee Weston19-Dec-08 0:41
Lee Weston19-Dec-08 0:41 
GeneralGreat example.... Pin
Kebrite8-Feb-08 17:57
Kebrite8-Feb-08 17:57 
GeneralExcellent article Pin
Nishant Rana (Nishu)28-Nov-07 2:36
Nishant Rana (Nishu)28-Nov-07 2:36 
NewsTwo other related encryption articles in CodeProject ... Pin
Tony Selke27-Sep-07 6:53
Tony Selke27-Sep-07 6:53 
QuestionCan you give the old version of framework 1.1,thank you! Pin
qushui11-Mar-07 21:52
qushui11-Mar-07 21:52 
AnswerRe: Can you give the old version of framework 1.1,thank you! Pin
Joel Hess13-Jun-07 13:54
Joel Hess13-Jun-07 13:54 
Generalkey length Pin
Cris C.2-Mar-07 2:50
Cris C.2-Mar-07 2:50 
GeneralRe: key length Pin
Joel Hess13-Jun-07 13:55
Joel Hess13-Jun-07 13:55 
GeneralRe: key length Pin
vurso7861-Jul-07 8:32
vurso7861-Jul-07 8:32 
GeneralRe: key length Pin
sachinmulange13-Aug-07 2:38
sachinmulange13-Aug-07 2:38 
GeneralThe other way around Pin
daviddastar14-Dec-06 19:25
daviddastar14-Dec-06 19:25 
Generalerror : system.FormatException Pin
zhao53430-May-06 23:54
zhao53430-May-06 23:54 
GeneralRe: error : system.FormatException Pin
zhao53431-May-06 22:16
zhao53431-May-06 22:16 

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

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