1

i planed to encrypt and decrypt the password entered in my application and my encryption is working and the data in the db is in encrypted form,but while it comes to the matter of decrypting and retrieving the data from the db, It is showing an error..

The input is not a valid Base-64 string as it contains a non-base 64 character, more  than two padding characters, or a non-white space character among the padding characters. 

and the line showing the error is..

   byte[] todecode_byte = Convert.FromBase64String(password);

code:

new.aspx.cs:(encryption)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace WebApplication5
{
    public partial class WebForm6 : System.Web.UI.Page
    {
        SqlConnection connection;
        protected void Page_Load(object sender, EventArgs e)
        {
            connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
            con1.Open();

            SqlCommand cmd1 = new SqlCommand("select * from admin where USERNAME=@USERNAME and PASSWORD=@PASSWORD ", con1);
            cmd1.Parameters.AddWithValue("@username", txtUserName.Text);
            cmd1.Parameters.AddWithValue("@password", txtPassword.Text);
            SqlDataReader dr = cmd1.ExecuteReader();
            if (dr.HasRows)
            {
                ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('userName is already availables')</script>");

            }

            else
            {

                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
                con.Open();
                string strQuery = "insert into admin( USERNAME,PASSWORD) values('" + txtUserName.Text + 
                   "','" +  EncodePasswordToBase64(txtPassword.Text) + "')";
                connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
                connection.Open();
                SqlCommand cmd = new SqlCommand(strQuery, connection);
                cmd.ExecuteNonQuery();
                connection.Close();
                Response.Redirect("login.aspx");

            }

            con1.Close();
        }
        public static string EncodePasswordToBase64(string password)
        {
            try
            {
                byte[] encData_byte = new byte[password.Length];
                encData_byte = System.Text.Encoding.UTF8.GetBytes(password);
                string encodedData = Convert.ToBase64String(encData_byte);
                return encodedData;
            }
            catch (Exception ex)
            {
                throw new Exception("Error in base64Encode" + ex.Message);
            }
        }

    }
}

login.aspx.cs:(decryption)

using System;
using System.Collections;
using System.Configuration;
using System.Data;
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.Security.Cryptography;
using System.Data.SqlClient;


namespace WebApplication5
{
    public partial class WebForm4 : System.Web.UI.Page
    {
        SqlConnection connection;
        protected void Page_Load(object sender, EventArgs e)
        {
            connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
            con1.Open();
            SqlCommand cmd1 = new SqlCommand("select * from admin where USERNAME=@USERNAME and DecodeFrom64(PASSWORD=@PASSWORD) ", con1);
            cmd1.Parameters.AddWithValue("@username", txtUserName.Text);
            cmd1.Parameters.AddWithValue("@password", DecodeFrom64(txtPassword.Text));
            SqlDataAdapter da = new SqlDataAdapter(cmd1);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                Response.Redirect("emplist.aspx");
            }
            else
            {
                ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
            }
            con1.Close();
        }
        protected void btnClear_Click(object sender, EventArgs e)
        {
            txtUserName.Text = "";
            txtPassword.Text = "";
        }
        public string DecodeFrom64(string password)
        {
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            System.Text.Decoder utf8Decode = encoder.GetDecoder();
            byte[] todecode_byte = Convert.FromBase64String(password);
            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            char[] decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            string result = new String(decoded_char);
            return result;
        }

    }

}

plz can any one help me on this process......,

1 Answer 1

5

Besides everything,, you call the function wrong. You call it as following:

DecodeFrom64(txtPassword.Text)

I can tell you,, I think that txtPassword.Text does not contain a Base64 string.


You are trying too hard in the DecodeFrom64 function:

public string DecodeFrom64(string password)
{
    return System.Text.UTF8.GetString(Convert.FromBase64String(password));
}

You have to do the opposite of the encode function in reverse:

byte[] encData_byte = new byte[password.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(password);
string encodedData = Convert.ToBase64String(encData_byte);

The last thing you do is Convert.ToBase64String so you must Convert.FromBase64String. Then before that you used System.Text.Encoding.UTF8.GetBytes. The opposite of that function is System.Text.UTF8.GetString. And as you can see in my answer you can put that all together in 1 line.:

System.Text.UTF8.GetString(Convert.FromBase64String(password));

But you don't encrypt passwords, you only apply obfuscation to them. If I hacked your database and saw those passwords I can easily crack them. I just have to enter them in a site like http://www.motobit.com/util/base64-decoder-encoder.asp or write my own small program and I have all the plain passwords.

If you want to save passwords to a database you could better use a hash. If you create and save a hash of a password to a database then when a hacker gets your database he/she can't see the real password because you cant reverse a hash like for example base64.

If someone is trying to log in to you site you create a hash of the entered password and then see if the hash equals the saved hash. If it does the password is the same.

As a hashing algoritm I would recommend SHA512. It is currently one of the best there is. MD5 is older and there are rainbow tables out there which can crack a MD5 in no time.

Sign up to request clarification or add additional context in comments.

2 Comments

@user2189723 who is nunespascal? :p But I am currently writing an article on my site which talks about a small login system using hashes. Ill post the article link here soon so you could read that.
@user2189723 I finished writing the article. Read about it on my site: synercoding.com/Articles/2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.