简体   繁体   English

使用C#在ASP.NET中进行加密和解密

[英]encryption and decryption in asp.net with c#

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) 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:(decryption) 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 can any one help me on this process......, 请在这个过程中有人可以帮助我......,

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. 我可以告诉你,我认为txtPassword.Text不包含Base64字符串。


You are trying too hard in the DecodeFrom64 function: 您在DecodeFrom64函数中尝试过分:

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: 您必须相反地执行encode函数的相反操作:

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 . 您要做的最后一件事是Convert.ToBase64String因此您必须Convert.FromBase64String Then before that you used System.Text.Encoding.UTF8.GetBytes . 然后,在此之前,您使用了System.Text.Encoding.UTF8.GetBytes The opposite of that function is System.Text.UTF8.GetString . 该函数的对面是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. 我只需要在类似http://www.motobit.com/util/base64-decoder-encoder.asp的站点中输入它们,或编写自己的小程序,便拥有所有普通密码。

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. 如果您创建密码的哈希并将其保存到数据库,那么当黑客获取您的数据库时,他/她将看不到真实密码,因为您无法反转哈希,例如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. 作为哈希算法,我建议使用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. MD5较旧,并且有彩虹表可以立即破解MD5。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM