Solved

Encryption Decryption issues - key size

Posted on 2008-10-03
7
1,955 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
ID: 22647704
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
ID: 22664691
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
ID: 22666897
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
ID: 22679209
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
ID: 22686145
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

895 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

16 Experts available now in Live!

Get 1:1 Help Now