SYSK 233: How to Decrypt an ASP.NET Encrypted Data

During debugging and troubleshooting web applications, there are times when you need to decrypt a string that was encrypted by ASP.NET (see my yesterday’s post, http://blogs.msdn.com/irenak/archive/2006/11/02/sysk-232-why-are-there-four-http-get-requests-retrieving-an-ajax-enabled-web-page.aspx, for an example of such need). But since the IV (initialization vector) is randomly initialized, even if you specify the encryption algorithm and the key in the <machineKey> configuration section, it’s not worth the time trying to crack it… Instead, I prefer to use reflection to do the work for me.

 

Please note, that the code below should not be used in production code! It’s only meant for debugging and troubleshooting, and it may break in future versions of the .NET framework if DecryptString private method changes.

 

1. Add a web page (e.g. DecryptData.aspx) to your web application. For the code to work, it must run in the same appdomain as the web application that created your encrypted string.

2. Add a text box where you will type in the encrypted string.

3. Add a label where you’ll display decrypted results.

4. Add a button.

5. In code-behind on button click event, add the following code:

System.Reflection.BindingFlags bf = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static;

System.Reflection.MethodInfo DecryptString = typeof(System.Web.UI.Page).GetMethod("DecryptString", bf);

DecryptedData.Text = DecryptString.Invoke(null, new object[] { EncryptedData.Text } ) as string;

 

That’s all there is to it…