Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2066
  • Last Modified:

Encryption Decryption issues - key size

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
centdevs
Asked:
centdevs
  • 3
  • 2
1 Solution
 
angus_young_acdcCommented:
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
 
centdevsAuthor Commented:
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
 
angus_young_acdcCommented:
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
 
centdevsAuthor Commented:
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
 
angus_young_acdcCommented:
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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now