Discuz!NT官方社区

首页 » Discuz!NT开发与测试 » Discuz!NT整合 » 独立登录NT系统的代码,从NT源码中分离出来的,仅作参考
qiancheng509 - 2008-5-23 12:29:00
NT密码MD5加密:

    public static string MD5(string toCryString)
    {
        MD5CryptoServiceProvider hashmd5;
        hashmd5 = new MD5CryptoServiceProvider();
        return BitConverter.ToString(hashmd5.ComputeHash(System.Text.Encoding.Default.GetBytes(toCryString))).Replace("-", "").ToLower();//把所有字符变小写
    }


qiancheng509 - 2008-5-23 12:31:00
基类:

public class TypeParse
{
  public static int StrToInt(object Expression, int defValue)
    {

        if (Expression != null)
        {
            string str = Expression.ToString();
            if (str.Length > 0 && str.Length <= 11 && Regex.IsMatch(str, @"^[-]?[0-9]*$"))
            {
                if ((str.Length < 10) || (str.Length == 10 && str[0] == '1') || (str.Length == 11 && str[0] == '-' && str[1] == '1'))
                {
                    return Convert.ToInt32(str);
                }
            }
        }
        return defValue;
    }


/// <summary>
/// 加密
/// </summary>
public class DES
{


    //默认密钥向量
    private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };


    /// <summary>
    /// DES加密字符串
    /// </summary>
    /// <param name="encryptString">待加密的字符串</param>
    /// <param name="encryptKey">加密密钥,要求为8位</param>
    /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
    public static string Encode(string encryptString, string encryptKey)
    {
        encryptKey = GetSubString(encryptKey, 8, "");
        encryptKey = encryptKey.PadRight(8, ' ');
        byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
        byte[] rgbIV = Keys;
        byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
        DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
        MemoryStream mStream = new MemoryStream();
        CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
        cStream.Write(inputByteArray, 0, inputByteArray.Length);
        cStream.FlushFinalBlock();
        return Convert.ToBase64String(mStream.ToArray());

    }

    /// <summary>
    /// DES解密字符串
    /// </summary>
    /// <param name="decryptString">待解密的字符串</param>
    /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
    /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
    public static string Decode(string decryptString, string decryptKey)
    {
        try
        {
            decryptKey = GetSubString(decryptKey, 8, "");
            decryptKey = decryptKey.PadRight(8, ' ');
            byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
            byte[] rgbIV = Keys;
            byte[] inputByteArray = Convert.FromBase64String(decryptString);
            DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();

            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Encoding.UTF8.GetString(mStream.ToArray());
        }
        catch
        {
            return "";
        }

    }

    /// <summary>
    /// 字符串如果操过指定长度则将超出的部分用指定字符串代替
    /// </summary>
    /// <param name="p_SrcString">要检查的字符串</param>
    /// <param name="p_Length">指定长度</param>
    /// <param name="p_TailString">用于替换的字符串</param>
    /// <returns>截取后的字符串</returns>
    public static string GetSubString(string p_SrcString, int p_Length, string p_TailString)
    {
        return GetSubString(p_SrcString, 0, p_Length, p_TailString);
    }


    /// <summary>
    /// 取指定长度的字符串
    /// </summary>
    /// <param name="p_SrcString">要检查的字符串</param>
    /// <param name="p_StartIndex">起始位置</param>
    /// <param name="p_Length">指定长度</param>
    /// <param name="p_TailString">用于替换的字符串</param>
    /// <returns>截取后的字符串</returns>
    public static string GetSubString(string p_SrcString, int p_StartIndex, int p_Length, string p_TailString)
    {


        string myResult = p_SrcString;

        //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3)
        if (System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\u0800-\u4e00]+") ||
            System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\xAC00-\xD7A3]+"))
        {
            //当截取的起始位置超出字段串长度时
            if (p_StartIndex >= p_SrcString.Length)
            {
                return "";
            }
            else
            {
                return p_SrcString.Substring(p_StartIndex,
                                              ((p_Length + p_StartIndex) > p_SrcString.Length) ? (p_SrcString.Length - p_StartIndex) : p_Length);
            }
        }


        if (p_Length >= 0)
        {
            byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString);

            //当字符串长度大于起始位置
            if (bsSrcString.Length > p_StartIndex)
            {
                int p_EndIndex = bsSrcString.Length;

                //当要截取的长度在字符串的有效长度范围内
                if (bsSrcString.Length > (p_StartIndex + p_Length))
                {
                    p_EndIndex = p_Length + p_StartIndex;
                }
                else
                {  //当不在有效范围内时,只取到字符串的结尾

                    p_Length = bsSrcString.Length - p_StartIndex;
                    p_TailString = "";
                }



                int nRealLength = p_Length;
                int[] anResultFlag = new int[p_Length];
                byte[] bsResult = null;

                int nFlag = 0;
                for (int i = p_StartIndex; i < p_EndIndex; i++)
                {

                    if (bsSrcString[i] > 127)
                    {
                        nFlag++;
                        if (nFlag == 3)
                        {
                            nFlag = 1;
                        }
                    }
                    else
                    {
                        nFlag = 0;
                    }

                    anResultFlag[i] = nFlag;
                }

                if ((bsSrcString[p_EndIndex - 1] > 127) && (anResultFlag[p_Length - 1] == 1))
                {
                    nRealLength = p_Length + 1;
                }

                bsResult = new byte[nRealLength];

                Array.Copy(bsSrcString, p_StartIndex, bsResult, 0, nRealLength);

                myResult = Encoding.Default.GetString(bsResult);

                myResult = myResult + p_TailString;
            }
        }

        return myResult;
    }


}


qiancheng509 - 2008-5-23 12:32:00
登录:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;

public partial class t : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        WriteUserCookie(Convert.ToInt32(this.TextBox1.Text.Trim()), Convert.ToInt32(this.TextBox4.Text.Trim()),

this.TextBox2.Text.Trim(), this.TextBox3.Text.Trim());
        Response.Write("OK");
    }
    /**/
    /// <summary>
    /// 写论坛cookie值
    /// </summary>
    /// <param name="strName">项</param>
    /// <param name="strValue">值</param>
    public static void WriteCookie(string strName, string strValue)
    {
        HttpCookie cookie = HttpContext.Current.Request.Cookies["dnt"];
        if (cookie == null)
        {
            cookie = new HttpCookie("dnt");
            cookie.Values[strName] = HttpUtility.UrlEncode(strValue);
        }
        else
        {

            cookie.Values[strName] = HttpUtility.UrlEncode(strValue);
            if (HttpContext.Current.Request.Cookies["dnt"]["expires"] != null)
            {
                int expires = StrToInt(HttpContext.Current.Request.Cookies["dnt"]["expires"].ToString(), 0);
                if (expires > 0)
                {
                    cookie.Expires = DateTime.Now.AddMinutes(StrToInt(HttpContext.Current.Request.Cookies["dnt"]

["expires"].ToString(), 0));
                }
            }
        }

        string cookieDomain = "xinkunming.com";
        if (cookieDomain != string.Empty && HttpContext.Current.Request.Url.Host.IndexOf(cookieDomain) > -1 &&

IsValidDomain(HttpContext.Current.Request.Url.Host))
            cookie.Domain = cookieDomain;

        HttpContext.Current.Response.AppendCookie(cookie);

    }


    /**/
    /// <summary>
    /// 写cookie值
    /// </summary>
    /// <param name="strName">名称</param>
    /// <param name="intValue">值</param>
    public static void WriteCookie(string strName, int intValue)
    {
        WriteCookie(strName, intValue.ToString());
    }

    /**/
    /// <summary>
    /// 写论坛登录用户的cookie
    /// </summary>
    /// <param name="uid">用户名</param>
    /// <param name="expires">cookie有效期</param>
    /// <param name="passwordkey">用户密码Key</param>
    /// <param name="templateid">用户当前要使用的界面风格</param>
    /// <param name="invisible">用户当前的登录模式(正常或隐身)</param>
    public static void WriteUserCookie(int uid, int expires, string password, string passwordkey)
    {
        HttpCookie cookie = new HttpCookie("dnt");
        cookie.Values["userid"] = uid.ToString();
        cookie.Values["password"] = HttpUtility.UrlEncode(SetCookiePassword(password, passwordkey));
        cookie.Values["tpp"] = "0";
        cookie.Values["ppp"] = "0";
        cookie.Values["pmsound"] = "1";
        cookie.Values["invisible"] = "0";
        cookie.Values["referer"] = "index.aspx";
        cookie.Values["sigstatus"] = "1";
        cookie.Values["expires"] = "0";
        if (expires > 0)
        {
            cookie.Expires = DateTime.Now.AddMinutes(expires);
        }
        string cookieDomain = "xinkunming.com";
        if (cookieDomain != string.Empty && HttpContext.Current.Request.Url.Host.IndexOf(cookieDomain) > -1 &&

IsValidDomain(HttpContext.Current.Request.Url.Host))
            cookie.Domain = cookieDomain;

        HttpContext.Current.Response.AppendCookie(cookie);
        //SetCookieExpires(expires);
    }

    /**/
    /// <summary>
    /// 获得论坛cookie值
    /// </summary>
    /// <param name="strName">项</param>
    /// <returns>值</returns>
    public static string GetCookie(string strName)
    {
        if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies["dnt"] != null &&

HttpContext.Current.Request.Cookies["dnt"][strName] != null)
        {
            return HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["dnt"][strName].ToString());
        }

        return "";
    }


    /**/
    /// <summary>
    /// 清除论坛登录用户的cookie
    /// </summary>
    public static void ClearUserCookie()
    {
        HttpCookie cookie = new HttpCookie("dnt");
        cookie.Values.Clear();
        cookie.Expires = DateTime.Now.AddYears(-1);
        string cookieDomain = "xinkunming.com";
        if (cookieDomain != string.Empty && HttpContext.Current.Request.Url.Host.IndexOf(cookieDomain) > -1 &&

IsValidDomain(HttpContext.Current.Request.Url.Host))
            cookie.Domain = cookieDomain;
        HttpContext.Current.Response.AppendCookie(cookie);

    }
    /// <summary>
    /// 将对象转换为Int32类型
    /// </summary>
    /// <param name="strValue">要转换的字符串</param>
    /// <param name="defValue">缺省值</param>
    /// <returns>转换后的int类型结果</returns>
    public static int StrToInt(object Expression, int defValue)
    {
        return TypeParse.StrToInt(Expression, defValue);
    }

    /// <summary>
    /// 返回密码密文
    /// </summary>
    /// <param name="password">密码明文</param>
    /// <param name="key">密钥</param>
    /// <returns></returns>
    public static string SetCookiePassword(string password, string key)
    {
        //                        if (password.Length < 32)
        //                        {
        //                                password = password.PadRight(32);
        //                        }
        return DES.Encode(password, key);
    }

    /// <summary>
    /// 是否为有效域
    /// </summary>
    /// <param name="host">域名</param>
    /// <returns></returns>
    public static bool IsValidDomain(string host)
    {
        Regex r = new Regex(@"^\d+$");
        if (host.IndexOf(".") == -1)
        {
            return false;
        }
        return r.IsMatch(host.Replace(".", string.Empty)) ? false : true;
    }
}


1
查看完整版本: 独立登录NT系统的代码,从NT源码中分离出来的,仅作参考