安全--解密

using  System;
using  System.Collections;
using  System.ComponentModel;
using  System.Data;
using  System.Drawing;
using  System.Web;
using  System.Web.SessionState;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.HtmlControls;
using  System.Data.SqlClient;
using  System.Web.Security;
using  System.Security.Cryptography;
using  System.Text;
using  System.IO;
namespace  CommandExample
{
    
/// <summary>
    
/// login 的摘要说明。
    
/// </summary>

    public class Login01 : System.Web.UI.Page
    
{
        
protected System.Web.UI.WebControls.Label Label1;
        
protected System.Web.UI.WebControls.TextBox tbName;
        
protected System.Web.UI.WebControls.TextBox tbPass;
        
protected System.Web.UI.WebControls.Button btnLoginBetter;
        
protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
        
protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator2;
        
protected System.Web.UI.WebControls.CheckBox PersistCookie;
        
protected System.Web.UI.WebControls.Label Label2;
    
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
// 在此处放置用户代码以初始化页面
        }


        
Web Form Designer generated code

        
private void btnLoginBetter_Click(object sender, System.EventArgs e)
        
{
            
bool bExist = AuthenticateUser(tbName.Text,tbPass.Text);
            
if(bExist)
            
{
                
//1) //创建一个验证票据//相当于产生一个COOKIE
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, tbName.Text,DateTime.Now,
                    DateTime.Now.AddMinutes(
30),PersistCookie.Checked,"User");
                
                
//2) //并且加密票据
                string cookieStr =  FormsAuthentication.Encrypt(ticket);
                
//3) 创建cookie//并且是以当前forms name=".MYWEB"命名,你可以自定义名称
                HttpCookie cookie =new HttpCookie(FormsAuthentication.FormsCookieName,cookieStr);//FormsAuthentication.FormsCookieName
                
                
if(PersistCookie.Checked) //如果用户选择了保存密码
                    cookie.Expires=ticket.Expiration;//设置cookie有效期为票据有效期
                
//cookie存放路径
                cookie.Path = FormsAuthentication.FormsCookiePath;
                
//将cookie写入到系统中cookie文件中
                Response.Cookies.Add(cookie);
                
// 4) do a redirect
                string strRedirect;
                strRedirect
=Request["ReturnUrl"].ToString();
                
                
if(strRedirect==null)
                    strRedirect
="default.aspx";
                Response.Redirect(strRedirect,
true);
            }

            
else
                Response.Write(
"<script language='javascript'>alert('用户名称或密码错误!')</script>");
            
        }

        
private bool ArraysEqual(byte[] array1,byte[] array2)
        
{
            
bool bResult = true;
            
if(array1==null)
                
throw new ArgumentNullException("array1");
            
if(array2==null)
                
throw new ArgumentNullException("array2");
            
if(array1.Length == array2.Length)
            
{
                
for(int i=0;i<array1.Length;i++)
                
{
                    
if(array1[i]!=array2[i])
                    
{
                        bResult 
= false;
                        
break;
                    }

                }

            }


            
return bResult;
        }

        
private bool AuthenticateUser(string strUserName, string strUserPass)
        
{
            SqlConnection con 
= new SqlConnection();
            con.ConnectionString 
= System.Configuration.ConfigurationSettings.AppSettings["DSN"];
            con.Open();
        
            
string strSql = "sp_getuserdetails";
            SqlCommand com 
= new SqlCommand(strSql,con);
            com.CommandType 
= CommandType.StoredProcedure;
            SqlParameter sqlpUser 
= new SqlParameter("@acctname",SqlDbType.NVarChar,64);
            sqlpUser.Value 
= tbName.Text;
            SqlParameter sqlpPasshash 
= new SqlParameter("@passhash",SqlDbType.NVarChar,50);
            sqlpPasshash.Direction 
= ParameterDirection.Output;
            SqlParameter sqlpPasssalt 
= new SqlParameter("@passsalt",SqlDbType.NVarChar,50);
            sqlpPasssalt.Direction 
= ParameterDirection.Output;
            com.Parameters.Add(sqlpUser);
            com.Parameters.Add(sqlpPasssalt);
            com.Parameters.Add(sqlpPasshash);
            com.ExecuteNonQuery();

            
string hash = com.Parameters["@passhash"].Value.ToString();
            
string salt = com.Parameters["@passsalt"].Value.ToString();

            
bool bExist = false;
            
if(hash==null||salt==null)
                bExist 
= false;
            
else
            
{
                
byte[] saltBits = Convert.FromBase64String(salt);
                
byte[] hashBits = Convert.FromBase64String(hash);
                
byte[] passBits = Encoding.Unicode.GetBytes(strUserPass);
                
                HashAlgorithm hashAlg 
= SHA1.Create();
                CryptoStream cs 
= new CryptoStream(Stream.Null,hashAlg,CryptoStreamMode.Write);
                cs.Write(passBits,
0,passBits.Length);
                cs.Write(saltBits,
0,saltBits.Length);
                cs.FlushFinalBlock();
                cs.Close();

                
byte[] digest = hashAlg.Hash;
                
if (ArraysEqual(digest,hashBits))
                    bExist 
= true;
                
else
                    bExist 
= false;
            }

            con.Close();
            
return bExist;
        }


    }

}

上面代码中使用了一个存储过程 sp_getuserdetails,这个存储过程的代码如下
CREATE   PROCEDURE  sp_getuserdetails
@acctname   varchar ( 64 ),
@passhash   varchar ( 50 ) out,
@passsalt   varchar ( 50 ) out
 
AS
select   @passhash = passwordHash, @passsalt = passwordSalt  from  formsUserInfo  where  userName = @acctname
GO

你可能感兴趣的:(安全)