Solved

Encryption Decryption issues - key size

Posted on 2008-10-03
7
1,941 Views
Last Modified: 2013-11-08
I am using example code from this earlier thread I posted (http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_23774576.html).

If I do a test such as the code snippet below, everything works fine.

I have a gridview where I am displaying this data.  One of the columns holds data that needs to be decrypted first.  In this case, when I decrypt the text I am getting an error:

"specified key is not a valid size for this algorithm"

For the purposes of this example, I am using the code exactly as is.  I honestly don't understand much about cryptography, I'm an absolute beginner, so the keys etc are a bit confusing to me.  If I understand correctly, I am assuming that I need to replace the:

private static byte[] key = { };

line with a call to web.config (or some other configuration file) to retrieve the actual value of the key.  If that is the case, what is the best way to get the value out of web.config and into the key variable?  I have read that you have to be careful about which method you use to put the bytes into the variable (ie I believe using UTF8 was recommended?).  I also read that the length of the key is important, but need an actual example of what an appropriate key would look like, or how to generate one.  

Again, since I am new at these concepts, I can understand what I am reading but am having difficulty applying the concepts, thanks.


lblEncrypted.Text = Utility.EncryptString("testing");

lblDecrypted.Text = Utility.DecryptString(lblEncrypted.Text);
 

The code from the related post:
 

using System;

using System.Data;

using System.Configuration;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.Text;

using System.Security.Cryptography;

using System.IO;

 

namespace QueryStringEncryption

{

    public class Cryptography

    {

        #region Fields

 

        private static byte[] key = { };

        private static byte[] IV = { 38, 55, 206, 48, 28, 64, 20, 16 };

        private static string stringKey = "!5663a#KN";

 

        #endregion

 

        #region Public Methods

 

        public static string Encrypt(string text)

        {

            try

            {

                key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8));

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                Byte[] byteArray = Encoding.UTF8.GetBytes(text);

                MemoryStream memoryStream = new MemoryStream();

                CryptoStream cryptoStream = new CryptoStream(memoryStream,

                    des.CreateEncryptor(key, IV), CryptoStreamMode.Write);

                cryptoStream.Write(byteArray, 0, byteArray.Length);

                cryptoStream.FlushFinalBlock();

                return Convert.ToBase64String(memoryStream.ToArray());

            }

            catch (Exception ex)

            {

                // Handle Exception Here

            }

            return string.Empty;

        }

 

 

 

        public static string Decrypt(string text)

        {

            try

            {

                key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8));

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                Byte[] byteArray = Convert.FromBase64String(text);

                MemoryStream memoryStream = new MemoryStream();

                CryptoStream cryptoStream = new CryptoStream(memoryStream,

                    des.CreateDecryptor(key, IV), CryptoStreamMode.Write);

                cryptoStream.Write(byteArray, 0, byteArray.Length);

                cryptoStream.FlushFinalBlock();

                return Encoding.UTF8.GetString(memoryStream.ToArray());

            }

            catch (Exception ex)

            {

                // Handle Exception Here

            }

            return string.Empty;

        }

 

 

 

        #endregion

 

    }

 

}

Open in new window

0
Comment
Question by:centdevs
  • 3
  • 2
7 Comments
 
LVL 15

Expert Comment

by:angus_young_acdc
Comment Utility
Chances are you were having the same issue as myself the other week.  The above code works fine for myself, when I created a form (and using only your code with a button reading a textBox string) and entered the text helloWorld I got the encrypted string H7xyJdQM1kw0/cMHJ0fvmw==, which was then decrypted back to helloWorld.

The problem may be that when you're pulling out the encrypted string (or putting it in) you are missing part of it.  I had the issue whereby the final "=" was not being stored and so I was getting an error about they key not being correct.  You can do a test to see what the encrypted string is before it is stored, and then check to see if the value is the same when it is.
0
 

Author Comment

by:centdevs
Comment Utility
I'll give this a try.  Do you know if this code should work across multiple servers?  Does this use the machine key or just like the example key in the code that I have specified above?
0
 
LVL 15

Expert Comment

by:angus_young_acdc
Comment Utility
That would all depend on how you've set up your application to handle the keys.  Although that's another question really that I would need to look up myself.  As for the keys if using the code you posted above, then it would continue to use the defined key (stringKey) during the encryption/decryption process
0
 

Author Comment

by:centdevs
Comment Utility
Unfortunately I haven't been able to figure this out yet.  Again, if I just pass a string in I can encrypt and decrypt fine.  I'm definitely getting all of the characters out of the database, I see in the debugger that the encrypted string is as expected.  I will get either a "bad data" or "specified key is not a valid size for this algorithm" error message.  I just can't get this to work consistently.  If I can't fix this code, could someone post some simple encrypt/decrypt code I can use that will work consistently (across multiple machines) and with data from a database?  I need actual code - I've been looking at a million tutorials, and it is just still very confusing for me.
0
 
LVL 15

Accepted Solution

by:
angus_young_acdc earned 500 total points
Comment Utility
This is examples that I used.  They, and indeed your own code, have not been a problem.  Are you sure that when you're taking data from your DB (or whatever source you currently us) that it is a string?

http://www.codeproject.com/KB/vb/VB_NET_TripleDES.aspx?fid=70758&fr=26#xx0xx - The most easy

http://www.codeproject.com/KB/security/DotNetCrypto.aspx
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now