?
Solved

Decrypting returns only partially correct value - help please!

Posted on 2008-10-20
2
Medium Priority
?
462 Views
Last Modified: 2012-05-05
Good evening Experts. I'm hoping somebody can help/bear with me on this one. (Not a web/c# person!)

The quick background: We have an ASP.Net/C# web application where people enter data, it gets encrypted and then imported into SQL2000. This application also will decrypt the data in order to let the users view their data. My goal is to return the data (in decrypted form). I have access only to the database, decryption method and password.

Problem: I'm super close! With help, I built a simple form (DecryptThis.aspx) that allows me to read the data from the database and use the same encryption method. Unfortunately, when the data is returned, it is only partially decrypted. For example: in the actual web app, if I were to enter "this is a test", my simple DescryptThis form will return something like "This is a .V”¾Öq="

This happens with every value in the database. When I return these values, they are about 75% decrypted.

I'm using the same decryption method and password that the web app uses. It's so close but I've tried everything i can think of - I've written the simple form (code attached) and also tried to do this in SQL using CLR sproc. Same results - it decrypts the values only partially. I'm at a total loss. Is this something simple I'm missing!?
 
The person who wrote the web app is long gone but I know it uses c#, .net (2005?), PasswordDerviceBytes and Rijndael.

Can anybody please help me? I'd really appreciate!

---- FILE 1: the method
using System;
using System.IO;
using System.Security.Cryptography;
 
namespace HelpMe
{
    /// <summary>
    /// Summary description for Encrypt.
    /// </summary>
    public class EncryptDecrypt
    {
        private const string Password = "The Password";
        public EncryptDecrypt()
        {
        }
 
        // Encrypt a byte array into a byte array using a key and an IV
        public static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV)
        {
            MemoryStream ms = new MemoryStream();
 
            Rijndael alg = Rijndael.Create();
 
            alg.Key = Key;
            alg.IV = IV;
 
            CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);
 
            cs.Write(clearData, 0, clearData.Length);
 
            cs.Close();
 
            byte[] encryptedData = ms.ToArray();
 
            return encryptedData;
        }
 
 
        // Encrypt a string into a string using a password
        //    Uses Encrypt(byte[], byte[], byte[])
        public static string Encrypt(string clearText)
        {
            if (clearText.Length == 0)
                return "";
            try
            {
                byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
 
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
                    new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,  0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
 
                byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
 
                //return Convert.ToBase64String(encryptedData); 
                return System.Text.Encoding.Unicode.GetString(encryptedData);
            }
            catch
            {
            }
            return "";
        }
 
        // Decrypt a byte array into a byte array using a key and an IV
        public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
        {
            MemoryStream ms = new MemoryStream();
 
            Rijndael alg = Rijndael.Create();
            alg.Key = Key;
            alg.IV = IV;
 
            CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
 
            cs.Write(cipherData, 0, cipherData.Length);
 
            cs.Close();
 
            byte[] decryptedData = ms.ToArray();
 
            return decryptedData;
        }
 
        // Decrypt a string into a string using a password 
        //    Uses Decrypt(byte[], byte[], byte[]) 
        public static string Decrypt(string cipherText)
        {
            try
            {
                //byte[] cipherBytes = Convert.FromBase64String(cipherText); 
                byte[] cipherBytes = System.Text.Encoding.Unicode.GetBytes(cipherText);
 
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                
                byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
                return System.Text.Encoding.Unicode.GetString(decryptedData);
            }
            catch (Exception e)
            {
                string t = e.Message.ToString();
                e.Message.ToString();
                //stop point
            }
            return "";
        }
 
    }
}
 
----- FILE2: SIMPLE FORM
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DecryptThis.aspx.cs" Inherits="DecryptThis" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
	<HEAD>
		<title>DecryptThis</title>
		<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
		<meta name="CODE_LANGUAGE" Content="C#">
		<meta name="vs_defaultClientScript" content="JavaScript">
		<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
	</HEAD>
	<body MS_POSITIONING="GridLayout">
		<form id="Form1" method="post" runat="server">
			<asp:TextBox id="txtCustomSql" style="Z-INDEX: 101; LEFT: 120px; POSITION: absolute; TOP: 80px"
				runat="server" Width="744px" Height="144px" TextMode="MultiLine"></asp:TextBox>
			<asp:Button id="btnSubmit" style="Z-INDEX: 102; LEFT: 800px; POSITION: absolute; TOP: 248px"
				runat="server" Text="Submit"></asp:Button>
			<asp:DataGrid id="dgResultSet" style="Z-INDEX: 103; LEFT: 128px; POSITION: absolute; TOP: 304px"
				runat="server" Visible="False"></asp:DataGrid>
			<asp:Label id="lblDescription" style="Z-INDEX: 104; LEFT: 120px; POSITION: absolute; TOP: 48px"
				runat="server" Width="456px">Enter SQL statement (which table/field)</asp:Label>
			<asp:Label id="lblErrorText" style="Z-INDEX: 105; LEFT: 352px; POSITION: absolute; TOP: 312px"
				runat="server" Width="448px" Visible="False"></asp:Label>
			<asp:TextBox id="txtColumnsToDecrypt" style="Z-INDEX: 106; LEFT: 464px; POSITION: absolute; TOP: 248px"
				runat="server" Width="326px"></asp:TextBox>
			<asp:Label id="lblColumnsToDecrypt" style="Z-INDEX: 107; LEFT: 128px; POSITION: absolute; TOP: 248px"
				runat="server" Width="312px">Columns To Decrypt (0 based, comma seperated):</asp:Label>
		</form>
	</body>
</html>
 
----- FILE3: SIMPLE FORM .cs
 
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
 
 
public partial class DecryptThis : System.Web.UI.Page
{
 
    public SqlConnection conn = null;
    public SqlCommand cmd = null;
 
 
    public int[] ColumnsToDecrypt
    {
        get
        {
            if (txtColumnsToDecrypt.Text == "")
            {
                return new int[0];
            }
            else
            {
                string str = txtColumnsToDecrypt.Text.Replace(" ", "");
                string[] s = str.Split(',');
                int[] i = new int[s.Length];
 
                for (int len = 0; len < s.Length; len++)
                {
                    i.SetValue((Convert.ToInt32(s[len])), len);
                }
                return i;
 
 
            }
        }
    }
 
    private void Page_Load(object sender, System.EventArgs e)
    {
        // Put user code to initialize the page here
        if (IsPostBack)
        {
 
            dgResultSet.Visible = true;
            lblErrorText.Text = String.Empty;
            lblErrorText.Visible = false;
        }
    }
 
    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
        //
        InitializeComponent();
        base.OnInit(e);
    }
 
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);
        this.Load += new System.EventHandler(this.Page_Load);
 
    }
    #endregion
 
    private void btnSubmit_Click(object sender, System.EventArgs e)
    {
        if (txtCustomSql.Text != "")
        {
            try
            { 
 
                DataTable dtable = this.ExecuteSql(txtCustomSql.Text);
                DataTableDecrypt(dtable, ColumnsToDecrypt);
                this.dgResultSet.DataSource = dtable;
                this.dgResultSet.DataBind();
                this.dgResultSet.Visible = true;
            }
            catch (Exception ex)
            {
 
                lblErrorText.Text = ex.Message;
                lblErrorText.Visible = true;
            }
 
        }
        else
        {
 
            lblErrorText.Text = "No Query";
            lblErrorText.Visible = true;
        }
    }
 
    private DataTable ExecuteSql(string SqlQuery)
    {
        DataTable dt = new DataTable();
        SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=localDB;Integrated Security=SSPI");
        conn.Open();
        SqlCommand cmd = new SqlCommand(SqlQuery, conn);
                        
        try
        {
         
            SqlDataReader sdr = cmd.ExecuteReader();
 
            if (sdr.HasRows)
            {
                foreach (DataRow r in sdr.GetSchemaTable().Rows)
                {
                    dt.Columns.Add(r[0].ToString());
                }
                int row = 0;
                while (sdr.Read())
                {
                    dt.Rows.Add(dt.NewRow());
                    for (int i = 0; i < sdr.FieldCount; i++)
                    {
                        dt.Rows[row][i] = sdr.GetValue(i).ToString();
                    }
                    row++;
                }
            }
 
        }
        catch (Exception e)
        {
            lblErrorText.Text = e.Message;
            lblErrorText.Visible = true;
        }
        conn.Close();
        return dt;
    }
 
    private void DataTableDecrypt(DataTable dt, int[] decryptcolumns)
    {
        if (decryptcolumns == null)
        {
            return;
        }
 
        foreach (DataRow r in dt.Rows)
        {
            for (int i = 0; i < decryptcolumns.Length; i++)
            {
                r[decryptcolumns[i]] = HelpMe.EncryptDecrypt.Decrypt(r[decryptcolumns[i]].ToString());
            }
        }
    }
 
}

Open in new window

0
Comment
Question by:trpnbillie
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 8

Expert Comment

by:rpkhare
ID: 22766128
I suspect the way you are using the Decryption process. I would recommend you to replace your Encrypt/Decrypt code with this one:

Refer the second post by the author "hwsoderlund" in the below given link:
http://silverlight.net/forums/p/14449/49982.aspx

I am using it and it is working fine.
0
 

Accepted Solution

by:
trpnbillie earned 0 total points
ID: 22772846
hi, thanks for your response. it didn't work but i found something that did - build the solution in VS2003 on top of .net 1.1. :) thanks again!
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

If you thought ransomware was bad, think again! Doxware has the potential to be even more damaging.
The well known Cerber ransomware continues to spread this summer through spear phishing email campaigns targeting enterprises. Learn how it easily bypasses traditional defenses - and what you can do to protect your data.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
Suggested Courses

752 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