[Solved] Invalid length for a Base-64 char array or string while decrypting in ASP.Net

Last Reply 29 days ago By dharmendr

Posted one month ago

I have to encode numbers of Employees but while decrypting some numbers i get error of Invalid length for a Base-64 char array or string, when i change the key it works with that number but doesn't work for another. 

protected void Page_Load(object sender, EventArgs e)
{
    DataTable employeeList = blu.getAllEmployeesList();
    string tableRow = "";
    int i = 1;
    foreach (DataRow value in employeeList.Rows)
    {

        tableRow += "<tr>";
        tableRow += "<td>" + i + "</td>";
        tableRow += "<td>" + value["emp_Fullname"] + " " + "(" + value["EMP_ID"] + ")" + "</td>";
        tableRow += "<td>" + value["DEG_NAME"] + "</td>";
        tableRow += "<td>" + value["GRADE_NAME"] + "</td>";
        tableRow += "<td>" + value["DEPT_NAME"] + "</td>";
        tableRow += "<td>" + value["BRANCH_NAME"] + "</td>";
        tableRow += "<td>" + value["STATUS_NAME"] + "</td>";
        string emp_id = value["EMP_ID"].ToString();
        var encrytptedId = blu.EncryptString(emp_id);
        tableRow += "<td><div class='button-list'><a href='viewDetail?EMP_ID=" + encrytptedId + "' onserverclick='' runat='server' class='btn btn-info waves-effect w-md waves-light' >View Details </a></div></td>";
        tableRow += "</tr>";
        i++;
    }
    tableBody.Text = tableRow;
}

public string EncryptString(string clearText)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(clearBytes, 0, clearBytes.Length);
                cs.Close();
            }
            clearText = Convert.ToBase64String(ms.ToArray());
        }
    }
    return clearText;
}

public string DecryptString(string cipherText)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    byte[] cipherBytes = Convert.FromBase64String(cipherText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(cipherBytes, 0, cipherBytes.Length);
                cs.Close();
            }
            cipherText = Encoding.Unicode.GetString(ms.ToArray());
        }
    }
    return cipherText;
}

This Works for some Employee Id and doesnt works for some ids.

Posted 29 days ago

Hi thereallover0...,

While Encrypting for some string the EncryptString is generated with plus (+) symbol.

Since you are redirecting with query string the retrieved QueryString replaced the plus (+) with space.

+ sign has a semantic meaning in the query string. It is used to represent a space.

So you are getting the error.

You need to encode the EncryptString value and redirect to the url.

HTML

<asp:Label ID="tableBody" runat="server" />

Namespaces

using System.Data;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web;

Code

Default

protected void Page_Load(object sender, EventArgs e)
{
    DataTable employeeList = new DataTable();
    employeeList.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
    employeeList.Rows.Add(1, "Nancy Davolio", "USA");
    employeeList.Rows.Add(2, "Andrew Fuller", "USA");
    employeeList.Rows.Add(3, "Janet Leverling", "USA");
    employeeList.Rows.Add(4, "Margaret Peacock", "USA");
    employeeList.Rows.Add(5, "Steven Buchanan", "UK");
    employeeList.Rows.Add(6, "Michael Suyama", "UK");
    employeeList.Rows.Add(7, "Robert King", "UK");
    employeeList.Rows.Add(8, "Laura Callahan", "USA");
    employeeList.Rows.Add(9, "Anne Dodsworth", "UK");
    string tableRow = "";
    int i = 1;
    foreach (DataRow value in employeeList.Rows)
    {
        tableRow += "<tr>";
        tableRow += "<td>" + i + "</td>";
        tableRow += "<td>" + value["Id"] + "</td>";
        tableRow += "<td>" + value["Name"] + "</td>";
        tableRow += "<td>" + value["Country"] + "</td>";
        string emp_id = value["Id"].ToString();
        var encrytptedId = HttpUtility.UrlEncode(EncryptString(emp_id));
        tableRow += "<td><div class='button-list'><a href='viewDetail.aspx?EMP_ID=" + encrytptedId + "' onserverclick='' runat='server' class='btn btn-info waves-effect w-md waves-light' >View Details </a></div></td>";
        tableRow += "</tr>";
        i++;
    }
    tableBody.Text = tableRow;
}

public string EncryptString(string clearText)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(clearBytes, 0, clearBytes.Length);
                cs.Close();
            }
            clearText = Convert.ToBase64String(ms.ToArray());
        }
    }
    return clearText;
}

viewDetail

protected void Page_Load(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(Request.QueryString["EMP_ID"]))
    {
        Response.Write(DecryptString(Request.QueryString["EMP_ID"]));
    }
}

public string DecryptString(string cipherText)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    byte[] cipherBytes = Convert.FromBase64String(cipherText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(cipherBytes, 0, cipherBytes.Length);
                cs.Close();
            }
            cipherText = Encoding.Unicode.GetString(ms.ToArray());
        }
    }
    return cipherText;
}