I have collected a reasonably good size library of C# helper files over the years.  The EncryptionHelper below is one of many which I plan to share.

using System;
using System.Security.Cryptography;
using System.Text;

namespace Common
{
    public static class EncryptionHelper
    {
        private const string cryptoKey = "cryptoKey";

        // The Initialization Vector for the DES encryption routine
        private static readonly byte[] IV =
            new byte[8] { 240, 3, 45, 29, 0, 76, 173, 59 };

        /// <summary>
        /// Encrypts provided string parameter
        /// </summary>
        public static string Encrypt(string s)
        {
            if (s == null || s.Length == 0) return string.Empty;

            string result = string.Empty;

            try
            {
                byte[] buffer = Encoding.ASCII.GetBytes(s);

                TripleDESCryptoServiceProvider des =
                    new TripleDESCryptoServiceProvider();

                MD5CryptoServiceProvider MD5 =
                    new MD5CryptoServiceProvider();

                des.Key =
                    MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(cryptoKey));

                des.IV = IV;
                result = Convert.ToBase64String(
                    des.CreateEncryptor().TransformFinalBlock(
                        buffer, 0, buffer.Length));
            }
            catch
            {
                throw;
            }

            return result;
        }

        /// <summary>
        /// Decrypts provided string parameter
        /// </summary>
        public static string Decrypt(string s)
        {
            if (s == null || s.Length == 0) return string.Empty;

            string result = string.Empty;

            try
            {
                byte[] buffer = Convert.FromBase64String(s);

                TripleDESCryptoServiceProvider des =
                    new TripleDESCryptoServiceProvider();

                MD5CryptoServiceProvider MD5 =
                    new MD5CryptoServiceProvider();

                des.Key =
                    MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(cryptoKey));

                des.IV = IV;

                result = Encoding.ASCII.GetString(
                    des.CreateDecryptor().TransformFinalBlock(
                    buffer, 0, buffer.Length));
            }
            catch
            {
                throw;
            }

            return result;
        }
    }
}

You may have noticed that my recent posts have been short and provide little more than featured code.   This is a new approach for me.  What do you think?  Should I continue to pepper in these quick code snippet posts with little commentary?

 

kick it on DotNetKicks.com

18 Comments to “C# Encryption / Decryption Helper Class”

  1. B2B says:

    well, I would say, that format is okay for me. The helper is great. Thanks

  2. Jesse says:

    Looks interesting, but I have one question:
    Is there a reason that your catch block in both of the methods simply re-throws? Wouldn’t simply not having the try/catch block there and allowing the exception to bubble up the stack to the caller achive the same result or am I missing something?

  3. Ben Griswold says:

    Hi Jesse,

    You are absolutely correct and you aren’t missing a thing. The try/catch/throw is providing zero programmatic value since this ‘pattern’ accomplishes the same thing as having no try/catch/throw at all.

    With that said, there is some method to my madness and the seemingly nugatory code was intentional. I don’t know about you, but I tend to wait until my code is working until I do my refactoring and clean up. For example, I may add XML Commments, error handling, logging or I may also optimize for performance. In some cases, there isn’t a lot to do, but I personally want a way to ‘mark’ the code as ‘closed.’ In other words, I’ve completed my review and I don’t need to give it further attention. In the two cases above, I can quickly see the routines are ‘closed’ since comments and exception handling are in place. If I opted to exclude the explicit exception handling, I might waste time reviewing the code again and I have fallen into this trap before.

    I don’t know. The try/catch/throw acts as a good indicator for me, but it isn’t for everyone. I definitely should consider stripping it out in future samples.

    Thanks for the comment,
    Ben

  4. [...] – bookmarked by 1 members originally found by nexusicon on 2008-08-15 C# Encryption / Decryption Helper Class http://johnnycoder.com/blog/20.....per-class/ – bookmarked by 2 [...]

  5. SelArom says:

    thank you for sharing this. There are many technical pages on the web about encryption but few just have a simple, and more important, USEFUL class like this. Works like a charm, thanks!

  6. Funny, worked at a company for (10) years and had tons of these types of snippets that I used from project to project. Then on a Friday I was layed off and by the time I got back to the cube was unable to login and get all the little bits of code that I had in a special area. I guess it would of been wrong to take them but you become attached to these things and over (10) years you have a ton of snippets like this!

    Bottom line first thing I needed on a contract which I have, hopefully NEVER going back to the corporate BS world, was a decent encrypt/decrypt routine and was kicking myself that I one could not remember how I did it before and moreover didn’t want to spend the time.A quick google search found this. I can’t say thanks enough. When I have some time I am going to add a section to my online site where I can start contributing back!

    BTW, I can figure out how to catch the exceptions! I have left your web-site references in the source code! Thanks Again!

  7. Ben Griswold says:

    @James – I’m happy to help. Thanks for the comment and best of luck with your new endeavor. Glad you have the exception thing figured out. ;) I really should update that code and leave people wondering what the heck the comments are talking about…

  8. jerreychen says:

    It’s great, Thanks!

  9. [...] johnnycoder.com/blog/2008/07/03/ [...]

  10. [...] C# Encryption / Decryption Helper Class | JohnnyCoder – [...]

  11. lalit says:

    Hi,

    I am using this code in my application. i could not get “IV” concept over here. I means do i need to save “IV” as constant for each execution ?

  12. Thanks for some other informative site. The place else may just I am getting that type of information written in such an ideal way? I’ve a mission that I’m just now operating on, and I’ve been at the look out for such info.

  13. jersey says:

    Have you ever thought about writing an e-book or guest authoring on other sites? I have a blog centered on the same information you discuss and would really like to have you share some stories/information. I know my audience would enjoy your work. If you are even remotely interested, feel free to send me an e mail.

  14. tire service says:

    What is the easiest way to add a blog to my existing website?

  15. What i do not understood is in reality how you are no longer really a lot more neatly-preferred than you might be right now. You’re so intelligent. You understand therefore significantly relating to this subject, produced me personally believe it from numerous varied angles. Its like women and men aren’t interested until it?¦s one thing to do with Lady gaga! Your own stuffs nice. Always care for it up!

  16. Hooran says:

    When I encrypt a string and want to decrypt it again it returns bad data. Does it have to do with padding?? It seems decrypting doesn’t read the data correctly.

    Thanks.

  17. UltimateDemon is actually a strong Website positioning automation application for your own articles and other content submission efforts. Along with UltimateDemon, you no longer need to have numerous products. It’s like a “one-stop shop” which offers you numerous website pages you could submit your material to. Unlike all the other applications, UltimateDemon gives a extremely user-friendly user interface with which has not been seen any where else. With UltimateDemon’s seamless distribution process, it’s easy to build a vast number of backlinks to your site and increase traffic without necessity to babysit the software. Presently there are just no other application out there that conduct process with similar degree of ease-of-use and hands free operation like UltimateDemon.

  18. bhargav says:

    I found this code very useful. But i have one question which is whether this encryption and decryption method affects performance of application?
    if yes then how much?

Leave a Reply

You can wrap your code with [ruby][/ruby] or [python][/python] blocks for syntax highlighting and you can use these traditional tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>