使用c#在asp.net中加密和解密

时间:2013-03-20 09:56:40

标签: c# asp.net-mvc encryption

我计划对我的应用程序中输入的密码进行加密和解密,我的加密工作正常,数据库中的数据是加密形式的,但是当涉及到解密和从数据库检索数据时,它是显示错误..

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. 

显示错误的行是..

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

new.aspx.cs:(加密)

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:(解密)

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任何人都可以帮助我完成这个过程......,

1 个答案:

答案 0 :(得分:5)

除了一切,你称这个功能错了。你称之为:

DecodeFrom64(txtPassword.Text)

我可以告诉你,我认为txtPassword.Text不包含Base64字符串。


你在DecodeFrom64函数中的尝试太过分了:

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

您必须反向执行编码功能的相反操作:

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

您要做的最后一件事是Convert.ToBase64String,因此您必须Convert.FromBase64String。 然后在此之前使用System.Text.Encoding.UTF8.GetBytes。与该函数相反的是System.Text.UTF8.GetString。正如你在我的回答中所看到的,你可以将它们放在一行中。:

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

但是你不加密密码,你只对它们应用混淆。如果我攻击你的数据库并看到那些密码我就可以轻易破解它们。我只需要在http://www.motobit.com/util/base64-decoder-encoder.asp这样的网站上输入它们,或者编写我自己的小程序,我就拥有所有普通密码。

如果要将密码保存到数据库,最好使用哈希。如果您创建并将密码的哈希值保存到数据库,那么当黑客获取您的数据库时,他/她无法看到真实密码,因为您无法反转哈希,例如base64。

如果有人试图登录您的网站,您可以创建输入密码的哈希值,然后查看哈希值是否等于保存的哈希值。如果是,密码是相同的。

作为哈希算法,我建议使用SHA512。它是目前最好的之一。 MD5较旧,有rainbow tables可以立即破解MD5。