下面代码可以很好的实现form登录验证,可我有一些疑问:1、这些代码把那几个变量保存到cookies中了?2、在login_info中除了用户名,我还有几个字段保存到cookies中(比如name,soles,zzjg等),应该怎么修改一下代码?3、保存的cookies是已加密过的,用的时候怎样解密使用?
谢谢 请各位高手赐教!
private bool ValidateUser(string userName,string passWord) 
{
SqlConnection conn;
SqlCommand cmd;
string lookupPassword = null; if ((null == userName) || ( 0 == userName.Length ) || ( userName.Length > 15 ) )
{
System.Diagnostics.Trace.WriteLine( "[ValidateUser] Input validation of userName failed." );
return false;
} if ( (  null == passWord ) || ( 0 == passWord.Length ) || ( passWord.Length > 25 ) )
{
System.Diagnostics.Trace.WriteLine( "[ValidateUser] Input validation of passWord failed." );
return false;
} try
{
conn = new SqlConnection(ConfigurationSettings.AppSettings["outSQLConnString"]);
conn.Open();
cmd = new SqlCommand( "Select loginpwd from login_info where loginname=@userName", conn );
cmd.Parameters.Add( "@userName", SqlDbType.VarChar, 25 );
cmd.Parameters["@userName"].Value = userName;
lookupPassword = (string) cmd.ExecuteScalar();
cmd.Dispose();
conn.Dispose();
}
catch ( Exception ex )
{
System.Diagnostics.Trace.WriteLine( "[ValidateUser] Exception " + ex.Message );
} if ( null == lookupPassword ) 
{
return false;
} return ( 0 == string.Compare( lookupPassword, passWord, false ) ); }
private void ImageButton1_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
if(ValidateUser(txtUserName.Value,txtPasswd.Value)) 
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt=new FormsAuthenticationTicket(1,txtUserName.Value,DateTime.Now,DateTime.Now.AddMinutes(30),chkPersistCookie.Checked,"your custom data"); //创建一个验证票据
cookiestr=FormsAuthentication.Encrypt(tkt);//并且加密票据
ck=new HttpCookie(FormsAuthentication.FormsCookieName,cookiestr);// 创建cookie
if(chkPersistCookie.Checked) //如果用户选择了保存密码
ck.Expires=tkt.Expiration;//设置cookie有效期
ck.Path=FormsAuthentication.FormsCookiePath;//cookie存放路径
Response.Cookies.Add(ck);
string strRedirect;
strRedirect=Request["ReturnUrl"];
if(strRedirect==null)
strRedirect="hy_net.aspx";
Response.Redirect(strRedirect,true);
}
else
Response.Redirect("login.aspx",true);
}

解决方案 »

  1.   

    3、保存的cookies是已加密过的,用的时候怎样解密使用?用对称加密算法加密,用时解密,下面是个现成的,注意修改密钥哦
    public class Encrypt
    {
    private SymmetricAlgorithm mobjCryptoService;
    private string Key; //密钥 public Encrypt()
    {
    mobjCryptoService = new RijndaelManaged();
    Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
    } //获得密钥
    private byte[] GetLegalKey()
    {
    string sTemp = Key;
    mobjCryptoService.GenerateKey(); byte[] bytTemp = mobjCryptoService.Key;
    int KeyLength = bytTemp.Length;

    if (sTemp.Length > KeyLength)
    {
    sTemp = sTemp.Substring(0, KeyLength);
    }
    else if (sTemp.Length < KeyLength)
    {
    sTemp = sTemp.PadRight(KeyLength, ' ');
    }

    return ASCIIEncoding.ASCII.GetBytes(sTemp);
    } //获得初始向量
    private byte[] GetLegalIV()
    {
    string sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
    mobjCryptoService.GenerateIV();
    byte[] bytTemp = mobjCryptoService.IV;
    int IVLength = bytTemp.Length;
    if (sTemp.Length > IVLength)
    sTemp = sTemp.Substring(0, IVLength);
    else if (sTemp.Length < IVLength)
    sTemp = sTemp.PadRight(IVLength, ' ');
    return ASCIIEncoding.ASCII.GetBytes(sTemp);
    } /// <summary>
    /// 对称加密Rijndael算法实现
    /// </summary>
    /// <param name="Source">待加密串</param>
    /// <returns>加密所得串</returns>
    public string Encrypto(string Source)
    {
    byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
    MemoryStream ms = new MemoryStream();
    mobjCryptoService.Key = GetLegalKey();
    mobjCryptoService.IV = GetLegalIV();
    ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
    CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
    cs.Write(bytIn, 0, bytIn.Length);
    cs.FlushFinalBlock();
    ms.Close();
    byte[] bytOut = ms.ToArray();
    return Convert.ToBase64String(bytOut);
    } /// <summary>
    /// 用Rijndael算法对字符串进行解密
    /// </summary>
    /// <param name="Source">待解密串</param>
    /// <returns>解密所得串</returns>
    public string Decrypto(string Source)
    {
    byte[] bytIn = Convert.FromBase64String(Source);
    MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
    mobjCryptoService.Key = GetLegalKey();
    mobjCryptoService.IV = GetLegalIV();
    ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
    CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
    StreamReader sr = new StreamReader(cs);
    return sr.ReadToEnd();
    }
    }
      

  2.   

    偶不单独保存字段信息,请参考一下代码: /// <summary>
    /// 论坛中所有页面的基类。
    /// </summary>
    public class ForumPage : System.Web.UI.Page
    {
    /// <summary>
    /// 初始化 ForumPage 类的新实例。
    /// </summary>
    public ForumPage()
    {
    }
    /// <summary>
    /// 获取当前已经登录的用户的信息,该信息使用 System.Collections.IDictionary 保存,并使用相应数据库字段的名称索引。如果还没有登录,则返回空引用。
    /// </summary>
    public System.Collections.IDictionary CurrentUserInfo
    {
    get
    {
    object o = this.Session["__CurrentUserInfo"];
    if(o is System.Collections.IDictionary)
    return (System.Collections.IDictionary)o;
    return null;
    }
    }
    /// <summary>
    /// 在用户登录后,并且用户的信息发生改变时,使用该方法重新加载当前用户的信息。如果用户还没有登录,则不产生任何效果。
    /// </summary>
    protected void RefreshCurrentUserInfo()
    {
    System.Collections.IDictionary d = this.CurrentUserInfo;
    if(d == null)
    return; this.Session["__CurrentUserInfo"] = AdoNetHelper.QueryRow("SELECT * FROM GBBS.GBBS_USERS WHERE USERID = " + d["USERID"]);
    } }
      

  3.   

    偶也贴个加密解密函数。 /// <summary>
    /// 加密指定的字符串为字节数组。
    /// </summary>
    /// <param name="password">要加密的字符串密码。</param>
    /// <returns>返回加密后的字节数组,长度不会超过 256。</returns>
    public static byte[] EncrptPassword(string password)
    {
    if(password == null)
    return null; if(password == "")
    return new byte[0]; byte[] buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(password); System.Security.Cryptography.RijndaelManaged rijndael = new System.Security.Cryptography.RijndaelManaged(); System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create();
    rijndael.Key = sha.ComputeHash(System.Text.UnicodeEncoding.Unicode.GetBytes("Key__" + password + "__Key"));
    rijndael.IV = sha.ComputeHash(System.Text.UnicodeEncoding.Unicode.GetBytes("IV__" + password + "__IV")); System.Security.Cryptography.ICryptoTransform encryptor = rijndael.CreateEncryptor(); System.IO.MemoryStream ms = new System.IO.MemoryStream();
    try
    {
    System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor, System.Security.Cryptography.CryptoStreamMode.Write); try
    {
    cs.Write(buffer, 0, buffer.Length);
    cs.FlushFinalBlock();
    }
    finally
    {
    cs.Close();
    }
    }
    finally
    {
    ms.Close();
    } buffer = ms.ToArray();
    byte [] bytes = new byte[64 + buffer.Length];
    Array.Copy(rijndael.Key, 0, bytes, 0, 32);
    Array.Copy(rijndael.IV, 0, bytes, 32, 32);
    Array.Copy(buffer, 0, bytes, 64, buffer.Length); return bytes;
    } /// <summary>
    /// 解密指定的字节数组密码。
    /// </summary>
    /// <param name="password">要解密的字节数组密码。</param>
    /// <returns>返回解密后的字符串密码。</returns>
    public static string DecrptPassword(byte[] password)
    {
    if(password == null)
    return null;
    if(password.Length == 0)
    return ""; if(password.Length < 64)
    throw new ArgumentException("无效的已加密的密码字节数组,其长度一定是大于 64 的值。"); System.Security.Cryptography.RijndaelManaged rijndael = new System.Security.Cryptography.RijndaelManaged(); byte [] buffer = new byte[32];
    Array.Copy(password, 0, buffer, 0, 32);
    rijndael.Key = buffer;
    Array.Copy(password, 32, buffer, 0, 32);
    rijndael.IV = buffer; buffer = new byte[password.Length - 64];
    Array.Copy(password, 64, buffer, 0, password.Length - 64); System.Security.Cryptography.ICryptoTransform decryptor = rijndael.CreateDecryptor(); System.IO.MemoryStream ms = new System.IO.MemoryStream(); try
    {
    System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, decryptor, System.Security.Cryptography.CryptoStreamMode.Write); try
    {
    cs.Write(buffer, 0, buffer.Length);
    cs.FlushFinalBlock();
    }
    finally
    {
    cs.Close();
    }
    }
    finally
    {
    ms.Close();
    } return System.Text.ASCIIEncoding.ASCII.GetString(ms.ToArray());
    }
    }
      

  4.   

    DataView dv=ds.Tables[0].DefaultView;
      

  5.   

    解密!
    public class Encrypt
    {
    private SymmetricAlgorithm mobjCryptoService;
    private string Key; 
    public Encrypt()
    {
    mobjCryptoService = new RijndaelManaged();
    Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
    }
    private byte[] GetLegalKey()
    {
    string sTemp = Key;
    mobjCryptoService.GenerateKey(); byte[] bytTemp = mobjCryptoService.Key;
    int KeyLength = bytTemp.Length;

    if (sTemp.Length > KeyLength)
    {
    sTemp = sTemp.Substring(0, KeyLength);
    }
    else if (sTemp.Length < KeyLength)
    {
    sTemp = sTemp.PadRight(KeyLength, ' ');
    }

    return ASCIIEncoding.ASCII.GetBytes(sTemp);
    }
      

  6.   

    1、这些代码把那几个变量保存到cookies中了?2、在login_info中除了用户名,我还有几个字段要保存到cookies中(比如name,soles,zzjg等),应该怎么修改一下代码?