Length of the data to decrypt is invalid

Discussion in 'ASP .Net Security' started by Bishoy George, Apr 5, 2006.

  1. I made a class based on RijndaelManaged class.
    I tied to separate the encrypting and decrypting processes.

    I now have the follwing resistant error:
    Length of the data to decrypt is invalid
    Line 70: cs.Read(fromEncrypted, 0, fromEncrypted.Length);

    I need a fix please.....

    The Code:
    --------------------------------------------------

    using System;

    using System.Data;

    using System.Configuration;

    using System.Web;

    using System.Web.Security;

    using System.Web.UI;

    using System.Web.UI.WebControls;

    using System.Web.UI.WebControls.WebParts;

    using System.Web.UI.HtmlControls;

    using System.IO;

    using System.Text;

    using System.Security.Cryptography;

    public class MyEncryption : System.Web.UI.Page

    {

    public MyEncryption()

    {

    }

    public static string Encrypt(string original)

    {

    byte[] encrypted;

    byte[] toEncrypt;

    byte[] key;

    byte[] IV;

    ASCIIEncoding textConverter = new ASCIIEncoding();

    toEncrypt = textConverter.GetBytes(original);

    RijndaelManaged myRijndael = new RijndaelManaged();

    myRijndael.GenerateKey();

    myRijndael.GenerateIV();

    key = myRijndael.Key;

    IV = myRijndael.IV;

    MyEncryption me = new MyEncryption();

    me.SetVariables(key, IV);

    MemoryStream ms = new MemoryStream();

    ICryptoTransform encryptor = myRijndael.CreateEncryptor(key,IV);

    CryptoStream cs = new CryptoStream(ms, encryptor,CryptoStreamMode.Write);

    cs.Write(toEncrypt, 0, toEncrypt.Length);

    cs.FlushFinalBlock();

    encrypted = ms.ToArray();

    string final = Convert.ToBase64String(encrypted);

    return final;

    }

    public static string Decrypt(string encryptedString)

    {

    byte[] key;

    byte[] IV;

    byte[] encrypted;

    byte[] fromEncrypted;

    MyEncryption me = new MyEncryption();

    me.GetVariables(out key, out IV);

    ASCIIEncoding textConverter = new ASCIIEncoding();

    encrypted = textConverter.GetBytes(encryptedString);

    fromEncrypted = new byte[encrypted.Length];

    MemoryStream ms = new MemoryStream(encrypted);

    RijndaelManaged myRijndael = new RijndaelManaged();

    ICryptoTransform decryptor = myRijndael.CreateDecryptor(key,IV);

    CryptoStream cs = new CryptoStream(ms, decryptor,CryptoStreamMode.Read);

    cs.Read(fromEncrypted, 0, fromEncrypted.Length);

    string decryptedString = Convert.ToBase64String(fromEncrypted);

    return decryptedString;

    }

    private void SetVariables(byte[] key, byte[] IV)

    {

    Session["key"] = key;

    Session["IV"] = IV;

    }

    private void GetVariables(out byte[] key, out byte[] IV)

    {

    key = (byte[])Session["key"];

    IV = (byte[])Session["IV"];

    }

    }
     
    Bishoy George, Apr 5, 2006
    #1
    1. Advertisements

  2. Bishoy George

    Jim Andersen Guest

    I can't see how you call those 2 functions, but I had something of the same,
    I encrypted a string, stored it in a database table, and later decrypted it.
    Had the same problem U did. Until I found out the field in the table wasn't
    long enough to hold all of the encrypted string. So I didn't pass the
    encrypted string to my decrypt fundtion. But a cut-off version of the
    string.

    /jim
     
    Jim Andersen, Apr 5, 2006
    #2
    1. Advertisements

  3. Dear Jim,
    In my case it is different, I just store the encrypted string in a Session
    Variable and get it again from that Session Variable.

    You said: "I can't see how you call those 2 functions"
    My Answer is: by a web page:
    - its url: http://testarea.nagyresearch.com/Test.aspx
    - its code:

    -------------------------- 1- Server html code ------------------------

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs"
    Inherits="NagyResearch.Test" %>

    <!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 runat="server">
    <title>Test Page</title>
    </head>
    <body onload="popup();">
    <form id="form1" runat="server">
    <div>
    <asp:Label ID="Label1" runat="server" Text="Test To
    Encrypt:"></asp:Label>
    <asp:TextBox ID="txtToEncrypt" runat="server"
    Width="274px"></asp:TextBox>
    <br />
    <br />
    <asp:Button ID="btnEncrypt" runat="server"
    OnClick="btnEncrypt_Click" Text="Encrypt!"
    Width="157px" /><br />
    <br />
    <asp:Label ID="lblResult" runat="server" Height="46px"
    Width="774px"></asp:Label><br />
    <br />
    <asp:Button ID="btnDecrypt" runat="server"
    OnClick="btnDecrypt_Click" Text="Decrypt!"
    Width="158px" /><br />
    <br />
    &nbsp;
    <asp:TextBox ID="txtDecryptedResult" runat="server" Height="53px"
    Width="770px"></asp:TextBox></div>
    </form>
    </body>
    </html>


    --------------------------------- 2- Code
    Behind -----------------------------------

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Text;

    namespace NagyResearch
    {
    public partial class Test : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnEncrypt_Click(object sender, EventArgs e)
    {
    lblResult.Text = MyEncryption.Encrypt(txtToEncrypt.Text);
    }
    protected void btnDecrypt_Click(object sender, EventArgs e)
    {
    txtDecryptedResult.Text = MyEncryption.Decrypt(lblResult.Text);
    }
    }
    }


    --------------------------------------------------- Class
    Code ------------------------------------------------

    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.IO;
    using System.Text;
    using System.Security.Cryptography;

    namespace NagyResearch
    {
    /// <summary>
    /// Summary description for MyEncryption
    /// </summary>
    public class MyEncryption : System.Web.UI.Page
    {
    public MyEncryption()
    {
    //
    // TODO: Add constructor logic here
    //
    }

    public static string Encrypt(string original)
    {
    byte[] encrypted; // here we put encrypted array of bytes
    byte[] toEncrypt; // here we put original array of bytes to
    encrypt them // also called buffer
    byte[] key; // Secret Key for encryption
    byte[] IV; // Initialization Vector

    // Convert a string to a byte array /////// VERY IMPORTANT
    ///////
    ASCIIEncoding textConverter = new ASCIIEncoding();
    toEncrypt = textConverter.GetBytes(original);

    // Create a new key and initialization vector
    RijndaelManaged myRijndael = new RijndaelManaged();
    myRijndael.GenerateKey();
    myRijndael.GenerateIV();
    // Get the key and IV
    key = myRijndael.Key;
    IV = myRijndael.IV;

    // Save Variables
    MyEncryption me = new MyEncryption();
    me.SetVariables(key, IV);

    // CryptoStream
    MemoryStream ms = new MemoryStream();
    ICryptoTransform encryptor = myRijndael.CreateEncryptor(key,
    IV);
    CryptoStream cs = new CryptoStream(ms, encryptor,
    CryptoStreamMode.Write);

    // Write all data to the crypto stream and flush it
    cs.Write(toEncrypt, 0, toEncrypt.Length);
    cs.FlushFinalBlock();

    // Get encrypted array of bytes
    encrypted = ms.ToArray();

    string final = Convert.ToBase64String(encrypted);

    return final;
    }

    public static string Decrypt(string encryptedString)
    {
    byte[] key;
    byte[] IV;
    byte[] encrypted;
    byte[] fromEncrypted;

    MyEncryption me = new MyEncryption();
    me.GetVariables(out key, out IV);

    ASCIIEncoding textConverter = new ASCIIEncoding();
    encrypted = textConverter.GetBytes(encryptedString);


    RijndaelManaged myRijndael = new RijndaelManaged();
    ICryptoTransform decryptor = myRijndael.CreateDecryptor(key,
    IV);

    MemoryStream ms = new MemoryStream(encrypted);

    CryptoStream cs = new CryptoStream(ms, decryptor,
    CryptoStreamMode.Read);

    fromEncrypted = new byte[encrypted.Length];

    cs.Read(fromEncrypted, 0, fromEncrypted.Length);

    string decryptedString = Convert.ToBase64String(fromEncrypted);

    return decryptedString;
    }

    private void SetVariables(byte[] key, byte[] IV)
    {
    Session["key"] = key;
    Session["IV"] = IV;
    }

    private void GetVariables(out byte[] key, out byte[] IV)
    {
    key = (byte[])Session["key"];
    IV = (byte[])Session["IV"];
    }

    public void CorruptVariables()
    {
    RijndaelManaged rm = new RijndaelManaged();
    rm.GenerateKey();
    rm.GenerateIV();

    Session["key"] = rm.Key;
    Session["IV"] = rm.IV;
    }
    }
    }
     
    Bishoy George, Apr 5, 2006
    #3
  4. I may be misunderstanding your code, but it looks like your decrypt function
    is taking the encrypted data which was encoded as a Base64 string and
    converting that back to binary use ASCII! That doesn't make any sense. If
    you encoded it with Base64, you must convert it back to binary with Base64.
    You would then take the decrypted data and convert that back to a string
    with ASCII.

    Note that using ASCII is generally a bad idea though. You probably should
    be using UTF8. UTF8 can round trip non-ASCII unicode characters, but will
    be the same binary data as ASCII for ASCII characters. It is a no lose
    proposition. ASCII inevitably ends up dropping characters when you least
    expect it.

    Joe K.

     
    Joe Kaplan \(MVP - ADSI\), Apr 6, 2006
    #4
  5. Dear Joe Kaplan,
    You are brilliant. Thank you. The code is working now.

    This is the new code after your 2 modifications:
    -------------------------------------
    using System;

    using System.Data;

    using System.Configuration;

    using System.Web;

    using System.Web.Security;

    using System.Web.UI;

    using System.Web.UI.WebControls;

    using System.Web.UI.WebControls.WebParts;

    using System.Web.UI.HtmlControls;

    using System.IO;

    using System.Text;

    using System.Security.Cryptography;

    namespace NagyResearch

    {

    /// <summary>

    /// Summary description for MyEncryption

    /// </summary>

    public class MyEncryption : System.Web.UI.Page

    {

    public MyEncryption()

    {

    //

    // TODO: Add constructor logic here

    //

    }

    public static string Encrypt(string original)

    {

    byte[] encrypted; // here we put encrypted array of bytes

    byte[] toEncrypt; // here we put original array of bytes to encrypt them //
    also called buffer

    byte[] key; // Secret Key for encryption

    byte[] IV; // Initialization Vector

    // Convert a string to a byte array /////// VERY IMPORTANT ///////

    UTF8Encoding utf8Converter = new UTF8Encoding();

    toEncrypt = utf8Converter.GetBytes(original);

    // Create a new key and initialization vector

    RijndaelManaged myRijndael = new RijndaelManaged();

    myRijndael.GenerateKey();

    myRijndael.GenerateIV();

    // Get the key and IV

    key = myRijndael.Key;

    IV = myRijndael.IV;

    // Save Variables

    MyEncryption me = new MyEncryption();

    me.SetVariables(key, IV);

    // CryptoStream

    MemoryStream ms = new MemoryStream();

    ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, IV);

    CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);

    // Write all data to the crypto stream and flush it

    cs.Write(toEncrypt, 0, toEncrypt.Length);

    cs.FlushFinalBlock();

    // Get encrypted array of bytes

    encrypted = ms.ToArray();

    string encryptedString = Convert.ToBase64String(encrypted);

    return encryptedString;

    }

    public static string Decrypt(string encryptedString)

    {

    byte[] key;

    byte[] IV;

    byte[] encrypted;

    byte[] fromEncrypted;

    MyEncryption me = new MyEncryption();

    me.GetVariables(out key, out IV);

    encrypted = Convert.FromBase64String(encryptedString);

    RijndaelManaged myRijndael = new RijndaelManaged();

    ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);

    MemoryStream ms = new MemoryStream(encrypted);

    CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);

    fromEncrypted = new byte[encrypted.Length];

    cs.Read(fromEncrypted, 0, fromEncrypted.Length);

    UTF8Encoding utf8Converter = new UTF8Encoding();

    string decryptedString = utf8Converter.GetString(fromEncrypted);

    return decryptedString;

    }

    private void SetVariables(byte[] key, byte[] IV)

    {

    Session["key"] = key;

    Session["IV"] = IV;

    }

    private void GetVariables(out byte[] key, out byte[] IV)

    {

    key = (byte[])Session["key"];

    IV = (byte[])Session["IV"];

    }

    public void CorruptVariables()

    {

    RijndaelManaged rm = new RijndaelManaged();

    rm.GenerateKey();

    rm.GenerateIV();

    Session["key"] = rm.Key;

    Session["IV"] = rm.IV;

    }

    }

    }
     
    Bishoy George, Apr 7, 2006
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.