程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 單點登陸

單點登陸

編輯:C++入門知識

using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.IO;
using System.Web.Security;
using System.Security.Cryptography;
using System.Web.Caching;

using Newtonsoft.Json;

using CN100.Member.IBLL.Modules;
using CN100.EnterprisePlatform.Wcf.Core;
using CN100.Member.IBLL;
using CN100.EnterprisePlatform.Wcf.Core.Config;
using CN100.ViewModel.Public;
using CN100.Member.Enums;


namespace CN100.Member.Permission
{
    /// <summary>
    /// 
    /// </summary>
    public class CurrentUser
    {
        private static string CookieName = "_Customer_Cn100_COM";
        private static string MenuSessionName = "_SubAccountMenuUrls";
        private static string LoginTimeCookie = "_Cn100_LoginTimeCookie";

        const string cartCookieName = "_mCartCacheName";
        const string messageCookieName = "_mMessageCookieName";

        const string PassWordFile = "Key.ini";
        const string cacheId = "cachePassword";
        /// <summary>
        /// 
        /// </summary>
        public const string filePassword = "Cn100cOM";
        const string defualtPassword = "Cn100.Co";
        const string appLoginName = "LoginPassWord";

        const string UserDataExpireMinutes = "UserDataExpireMinutes";


        /// <summary>
        ///登陸過期時間
        /// </summary>
        private static int ExpireMinutes
        {
            get
            {
                string strMin = System.Web.Configuration.WebConfigurationManager.AppSettings[UserDataExpireMinutes];
                if (!string.IsNullOrEmpty(strMin))
                {
                    int min = 0;
                    if (int.TryParse(strMin, out min))
                    {
                        return min;
                    }
                }

                return 30;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        protected static string configPassword = GetRSAPassWord();

        private static string GetRSAPassWord()
        {
            try
            {
                string strPwd = RSADecryption(System.Web.Configuration.WebConfigurationManager.AppSettings[appLoginName].ToString());
                return strPwd;
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
            }
            return "";
        }

        private static string GetPassWord()
        {
            string strPath = HttpContext.Current.Request.PhysicalApplicationPath + "/" + PassWordFile;
            object objPassword = WebCache.GetFromWebCache(cacheId);
            string strPassWord = "";

            if (objPassword != null)
            {
                strPassWord = objPassword.ToString();
            }
            else
            {
                if (File.Exists(strPath))
                {
                    FileStream stream = new FileStream(strPath, FileMode.Open, FileAccess.Read);
                    StreamReader reader = new StreamReader(stream);
                    strPassWord = reader.ReadToEnd();
                    strPassWord = DecryptDES(strPassWord, filePassword);
                    stream.Close();
                    reader.Close();

                    //寫入緩存
                    CacheDependency cacheDepen = new CacheDependency(strPath);
                    WebCache.WriteData(cacheId, cacheDepen, strPassWord);
                }
                else
                {
                    FileStream stream = new FileStream(strPath, FileMode.CreateNew, FileAccess.Write);
                    strPassWord = EncryptDES(defualtPassword, filePassword);
                    byte[] btPass = Encoding.UTF8.GetBytes(strPassWord);
                    stream.Write(btPass, 0, btPass.Length);
                    stream.Close();
                    strPassWord = defualtPassword;
                }
            }

            return strPassWord;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public bool isLogin()
        {
            lock (@Lock)
            {
                var cookie = CookieExt.GetCookie(CookieName);
                if (cookie != null)
                {
                    DateTime loginTime = GetLoginTime();

                    //延長cookie時間
                    // ExtendCookieTime(UserData);
                    if (loginTime.AddMinutes(ExpireMinutes) < DateTime.Now)
                    {
                        LogOut();
                        return false;
                    }
                    else
                    {
                        //延長登陸時間
                        ExtendCookieTime();
                    }

                    string UserData = CookieExt.GetCookieValueByName(CookieName);

                    if (!string.IsNullOrEmpty(UserData))
                    {
                        try
                        {

                            string decryptString = DecryptDES(UserData, configPassword);
                            var result = (LoginResult)JsonConvert.DeserializeObject(decryptString, typeof(LoginResult));
                            return true;
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex);
                        }
                    }
                }
                return false;
            }
        }

        /// <summary>
        /// 是否登陸
        /// </summary>
        /// <returns></returns>
        public static bool IsLogin()
        {
            CurrentUser user = new CurrentUser();
            return user.isLogin();
            //return HttpContext.Current.User.Identity.IsAuthenticated;
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public static bool LogOut()
        {
            try
            {
                //System.Web.Security.FormsAuthentication.SignOut();
                CookieExt.ClearCookie(CookieName);
                CookieExt.ClearCookie(messageCookieName);
                CookieExt.ClearCookie(cartCookieName);

                //清除登陸時間
                CookieExt.ClearCookie(LoginTimeCookie);
                HttpContext.Current.Session.Remove(LoginTimeCookie);
                //提現密碼
                CookieExt.ClearCookie("_CN100_DRACA_");
                //提現錯誤次數
                CookieExt.ClearCookie("_CN100_DRACOUNT_");

                //移除子帳號菜單權限
                if (HttpContext.Current.Session[MenuSessionName] != null)
                {
                    HttpContext.Current.Session.Remove(MenuSessionName);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public static object @Lock = new object();
        /// <summary>
        /// 獲取當前用戶信息
        /// </summary>
        public static LoginResult UserInfo
        {
            get
            {
                CurrentUser user = new CurrentUser();
                return user.GetUserInfo();
            }
        }

        /// <summary>
        /// 獲取用戶信息
        /// </summary>
        /// <returns></returns>
        public LoginResult GetUserInfo()
        {
            lock (@Lock)
            {
                LoginResult result = new LoginResult();
                if (IsLogin())
                {
                    string UserData = CookieExt.GetCookieValueByName(CookieName);
                    if (!string.IsNullOrEmpty(UserData))
                    {
                        try
                        {
                            string decryptString = DecryptDES(UserData, configPassword);
                            result = (LoginResult)JsonConvert.DeserializeObject(decryptString, typeof(LoginResult));


                            DateTime loginTime = GetLoginTime();

                            //延長cookie時間
                            // ExtendCookieTime(UserData);
                            if (loginTime.AddMinutes(ExpireMinutes) < DateTime.Now)
                            {
                                LogOutToLoginPage();
                                return new LoginResult();
                            }
                            else
                            {
                                //延長登陸時間
                                ExtendCookieTime();
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex);
                            RedirectToLoginPage();
                        }
                    }
                }
                return result;

            }
        }



        /// <summary>
        /// 延長用戶cookie時間
        /// </summary>
        public static void ExtendCookieTime()
        {
            //try
            //{
            //    if (HttpContext.Current.Session[LoginTimeCookie] != null)
            //    {
            //        DateTime time = Convert.ToDateTime(HttpContext.Current.Session[LoginTimeCookie]);
            //        if (time.AddMinutes(1) < DateTime.Now)
            //        {
            //            HttpContext.Current.Session[LoginTimeCookie] = DateTime.Now;
            //            CookieExt.SetCookie(LoginTimeCookie, DateTime.Now.ToString());
            //        }
            //    }
            //    else
            //    {
            //        HttpContext.Current.Session[LoginTimeCookie] = DateTime.Now;
            //        CookieExt.SetCookie(LoginTimeCookie, DateTime.Now.ToString());
            //    }

            //}
            //catch (Exception ex)
            //{
            //    Log.WriteLog(ex);
            //    CookieExt.SetCookie(LoginTimeCookie, DateTime.Now.ToString());
            //}
            CookieExt.SetCookie(LoginTimeCookie, DateTime.Now.ToString());
        }

        /// <summary>
        /// 獲取上次登陸時間
        /// </summary>
        /// <returns></returns>
        private static DateTime GetLoginTime()
        {
            if (CookieExt.GetCookie(LoginTimeCookie) != null)
            {
                DateTime loginTime = DateTime.Now;
                if (DateTime.TryParse(CookieExt.GetCookieValueByName(LoginTimeCookie), out loginTime))
                {
                    return loginTime;
                }
            }
            return DateTime.Now;
        }

        /// <summary>
        /// 登出返回登陸頁面
        /// </summary>
        public static void LogOutToLoginPage()
        {
            //System.Web.Security.FormsAuthentication.SignOut();
            LogOut();
            string url = GetReturnUrl();
            HttpContext.Current.Response.Redirect(FormsAuthentication.LoginUrl + "?ReturnUrl=" + url);
        }

        /// <summary>
        /// 登出並跳轉到默認頁面
        /// </summary>
        public static void LogOutToDefaultPage()
        {
            LogOut();
            HttpContext.Current.Response.Redirect(FormsAuthentication.DefaultUrl);
        }

        /// <summary>
        /// 轉到登陸頁面
        /// </summary>
        public static void RedirectToLoginPage()
        {

            string url = GetReturnUrl();
            HttpContext.Current.Response.Redirect(FormsAuthentication.LoginUrl + "?ReturnUrl=" + url);
        }

        /// <summary>
        /// 轉到默認頁面
        /// </summary>
        public static void RedirectToDefaultPage()
        {
            HttpContext.Current.Response.Redirect(FormsAuthentication.DefaultUrl);
        }

        /// <summary>
        /// 用戶名,如果是子帳號登陸,用父帳戶名
        /// </summary>
        public static string UserName
        {
            get
            {
                if (IsLogin())
                {
                    //return HttpContext.Current.User.Identity.Name;
                    return UserInfo.UserName;
                }
                return null;
            }
        }

        /// <summary>
        /// 保存用戶信息到cookie
        /// </summary>
        /// <param name="result"></param>
        public static void SaveUserCookie(LoginResult result)
        {
            //string userData = JsonConvert.SerializeObject(result);

            //FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
            //                                        result.UserName,
            //                                        DateTime.Now,
            //                                        DateTime.Now.AddMinutes(30), // value of time out property
            //                                        true, // Value of IsPersistent property
            //                                        userData,
            //                                        FormsAuthentication.FormsCookiePath);
            //string encryptedTicket = FormsAuthentication.Encrypt(ticket);
            //HttpCookie authCookie = new HttpCookie(CookieName, encryptedTicket);
            //HttpCookie authCookie = new HttpCookie(CookieName, encryptedTicket);
            //authCookie.Domain = FormsAuthentication.CookieDomain;
            //authCookie.Path = FormsAuthentication.FormsCookiePath;
            //authCookie.Expires = DateTime.Now.AddMinutes(30);
            //HttpCookie authCookie = new HttpCookie(CookieName, encryptedTicket);
            //authCookie.Domain = FormsAuthentication.CookieDomain;
            //authCookie.Path = FormsAuthentication.FormsCookiePath;
            //authCookie.Expires = DateTime.Now.AddMinutes(30);
            //if (HttpContext.Current.Request.Cookies[CookieName] != null)
            //{
            //    HttpContext.Current.Response.Cookies.Set(authCookie);
            //}
            //else
            //{
            //    HttpContext.Current.Response.Cookies.Add(authCookie);
            //}


            result.LoginTime = DateTime.Now;
            string encryptedTicket = DeserializeUserData(result);
            CookieExt.SetCookie(CookieName, encryptedTicket); //, DateTime.Now.AddMinutes(ExpireMinutes)

            //清除購物與信息緩存
            CookieExt.ClearCookie(cartCookieName);
            CookieExt.ClearCookie(messageCookieName);

            //保存登陸時間
            ExtendCookieTime();
            //移除子帳號菜單權限
            if (HttpContext.Current.Session[MenuSessionName] != null)
            {
                HttpContext.Current.Session.Remove(MenuSessionName);
            }
        }

        /// <summary>
        /// 序列化用戶信息
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public static string DeserializeUserData(LoginResult result)
        {
            string userData = JsonConvert.SerializeObject(result);
            string encryptedTicket = EncryptDES(userData, configPassword);
            return encryptedTicket;
        }

        /// <summary>
        /// 獲取當前用戶信息
        /// </summary>
        /// <returns></returns>
        public static LoginResult GetCurrentUserInfo()
        {
            lock (@Lock)
            {
                CurrentUser user = new CurrentUser();
                return user.GetUserInfo();
            }
        }

        /// <summary>
        /// 獲取
        /// </summary>
        /// <returns></returns>
        public static string GetReturnUrl()
        {
            string hosts = HttpContext.Current.Request.Headers["host"];
            if (string.IsNullOrEmpty(hosts))
            {
                hosts = HttpContext.Current.Request.Url.Host;
            }
            string pageUrl = HttpContext.Current.Request.Url.PathAndQuery;
            return HttpUtility.UrlEncode("http://" + hosts + pageUrl);
        }

        /// <summary>
        /// 根據用戶,判斷是否具有菜單ID權限
        /// </summary>
        /// <param name="menuID"></param>
        /// <param name="subAccountID"></param>
        /// <returns></returns>
        public static bool HasMenuIDBySubAccountID(long menuID, long subAccountID)
        {
            try
            {
                using (WcfTcpClient<IMemberUsers> client = WcfClients.Member.CreateClient<IMemberUsers>())
                {
                    return client.Channel.HasMenuIDBySubAccountID(subAccountID, menuID);
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
                return false;
            }
        }

        /// <summary>
        /// 當前用戶是否具有菜單權限
        /// </summary>
        /// <param name="menuID">菜單ID</param>
        /// <returns></returns>
        public static bool HasMenuID(long menuID)
        {
            if (UserInfo == null) return false;
            return HasMenuIDBySubAccountID(menuID, UserInfo.SubAccountID);

        }

        /// <summary>
        /// 根據用戶名,獲取有權限的菜單ID
        /// </summary>
        /// <param name="subAccountID">子帳號ID</param>
        /// <returns></returns>
        public static long[] GetMenuIDesBySubAccountID(long subAccountID)
        {
            try
            {
                using (WcfTcpClient<IMemberUsers> client = WcfClients.Member.CreateClient<IMemberUsers>())
                {
                    return client.Channel.GetMenuIDesBySubAccountID(subAccountID);
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
                return new long[] { };
            }

        }

        /// <summary>
        /// 獲取當前用戶有權限菜單ID
        /// </summary>
        /// <returns></returns>
        public static long[] GetMenuIDes()
        {
            if (UserInfo == null) return new long[] { };

            return GetMenuIDesBySubAccountID(UserInfo.SubAccountID);
        }

        private static IList<StoreMenuInfo> GetSubAccountMenu(long subAccount)
        {
            try
            {
                using (WcfTcpClient<IMemberUsers> client = WcfClients.Member.CreateClient<IMemberUsers>())
                {
                    IList<StoreMenuInfo> listMenu = client.Channel.GetStoreMenuBySubAccountID(subAccount);
                    string strCookie = JsonConvert.SerializeObject(listMenu);
                    //HttpContext.Current.Session.Add(MenuSessionName, listMenu);
                    return listMenu;
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
            }
            return new List<StoreMenuInfo>();
        }

        /// <summary>
        /// 判斷子帳號是否具有URL權限
        /// </summary>
        /// <param name="url"></param>
        /// <param name="subAccount"></param>
        /// <returns></returns>
        public static bool HasMenuOfSubAccount(string url, long subAccount)
        {
            //IList<StoreMenuInfo> listMenu = new List<StoreMenuInfo>();
            //if (HttpContext.Current.Session[MenuSessionName] != null)
            //{
            //    listMenu = HttpContext.Current.Session[MenuSessionName] as List<StoreMenuInfo>;
            //    if (listMenu == null)
            //    {
            //        listMenu = GetSubAccountMenu(subAccount);
            //    }
            //}
            //else
            //{
            //    listMenu = GetSubAccountMenu(subAccount);
            //}

            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@":\d+", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            System.Text.RegularExpressions.Regex IPreg = new System.Text.RegularExpressions.Regex(@"(\d{1,3}\.){3}\d{1,3}", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            if (IPreg.IsMatch(url))
            {
                string hosts = HttpContext.Current.Request.Headers["host"];
                if (string.IsNullOrEmpty(hosts))
                {
                    hosts = HttpContext.Current.Request.Url.Host;
                }
                string pageUrl = HttpContext.Current.Request.Url.PathAndQuery;
                url = "http://" + hosts + pageUrl;
            }
            else if (reg.IsMatch(url))
            {
                url = reg.Replace(url, "");
            }

            
            IList<StoreMenuInfo> listMenu = GetSubAccountMenu(subAccount);
            if (listMenu.Count > 0)
            {
                var instance = CN100.EnterprisePlatform.Configuration.DomainSection.Instance;
                foreach (var menu in listMenu)
                {
                    if (!string.IsNullOrEmpty(menu.DomainName))
                    {
                        if (instance.Urls[menu.DomainName] != null)
                        {
                            string menuUrl = instance.Urls[menu.DomainName].Url + menu.Url;
                            if (menuUrl.ToLower() == url.ToLower())
                            {
                                return true;
                            }
                        }
                    }

                }
            }
            Log.WriteLog(new Exception("子帳號來訪地址:" + url.ToString()));
            return false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool HasMenuOfSubAccount(string url)
        {
            if (CurrentUser.IsLogin())
            {
                long subAccountID = CurrentUser.UserInfo.SubAccountID;
                if (subAccountID > 0)
                {
                    return HasMenuOfSubAccount(url, subAccountID);
                }
            }
            return false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userType"></param>
        /// <returns></returns>
        public static int GetMessageCountByUserName(string userName, UserType userType)
        {
            try
            {
                using (WcfTcpClient<IUserMessageService> client = WcfClients.Member.CreateClient<IUserMessageService>())
                {
                    return client.Channel.GetUnReadMessageCount(userName, userType);
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
            }
            return 0;
        }

        /// <summary>
        /// 獲取未讀信息
        /// </summary>
        /// <returns></returns>
        public static int GetMessageCountByUserName()
        {
            if (IsLogin())
            {
                return GetMessageCountByUserName(UserName, GetCurrentUserInfo().UserType);
            }
            return 0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public static IList<ShopCart> GetShopCartQtyByUserID(long UserID)
        {
            try
            {
                using (WcfTcpClient<IMemberUsers> client = WcfClients.Member.CreateClient<IMemberUsers>())
                {
                    return client.Channel.GetShopCartQtyByUserID(UserID);
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
            }
            return new List<ShopCart>();
        }

        /// <summary>
        /// 獲取購物車數量
        /// </summary>
        /// <returns></returns>
        public static IList<ShopCart> GetShopCartQtyByUserID()
        {
            if (IsLogin())
            {
                return GetShopCartQtyByUserID(UserInfo.UserBaseID);
            }
            return new List<ShopCart>();
        }


        /// <summary>
        /// 申請店鋪流程過程中直接錄入地址時未滿足條件url跳轉
        /// </summary>
        public static void RedirectAlertPage()
        {
            //Response.Redirect(ConfigHelper.GetDomain("LoginURL") + "/AlertPage.aspx");
            HttpContext.Current.Response.Redirect(ConfigHelper.GetDomain("LoginURL") + "AlertPage.aspx");
        }

        #region 加密解密
        //默認密鑰向量
        private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        /**/
        /**/
        /**/
        private static DESCryptoServiceProvider des = new DESCryptoServiceProvider();

        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加密密鑰,要求為8位</param>
        /// <returns>加密成功返回加密後的字符串,失敗返回源串</returns>
        public static string EncryptDES(string encryptString, string encryptKey)
        {
            try
            {
                //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());

                byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(encryptString);
                des.Key = ASCIIEncoding.ASCII.GetBytes(encryptKey.Substring(0, 8));
                des.IV = ASCIIEncoding.ASCII.GetBytes(encryptKey.Substring(0, 8));
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();

                StringBuilder ret = new StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:X2}", b);
                }
                return ret.ToString();
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
                return encryptString;
            }
        }

        /**/
        /**/
        /**/
        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解密密鑰,要求為8位,和加密密鑰相同</param>
        /// <returns>解密成功返回解密後的字符串,失敗返源串</returns>
        public static string DecryptDES(string decryptString, string decryptKey)
        {
            try
            {
                //byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
                //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());
                byte[] inputByteArray = new byte[decryptString.Length / 2];
                for (int x = 0; x < decryptString.Length / 2; x++)
                {
                    int i = (Convert.ToInt32(decryptString.Substring(x * 2, 2), 16));
                    inputByteArray[x] = (byte)i;
                }
                des.Key = ASCIIEncoding.ASCII.GetBytes(decryptKey.Substring(0, 8));
                des.IV = ASCIIEncoding.ASCII.GetBytes(decryptKey.Substring(0, 8));
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
                return System.Text.Encoding.UTF8.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
                return decryptString;
            }
        }

        /// <summary>
        /// RSA 的密鑰產生 產生私鑰 和公鑰 
        /// </summary>
        /// <param name="xmlKeys"></param>
        /// <param name="xmlPublicKey"></param>
        public void RSAKey(out string xmlKeys, out string xmlPublicKey)
        {
            System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            xmlKeys = rsa.ToXmlString(true);
            xmlPublicKey = rsa.ToXmlString(false);
        }

        const string PUBLICKEY = "<RSAKeyValue><Modulus>1E1BqQ0uipllOGPMKB4YO/ZutHO0pfQz6jQKFs1y958Vm8YO77APoI65hFYZbFLer3MKx2Obp1Y0DyUyuNIes+IhS7I4nHBS4igdvhohUZDhLLphiuDZ3i5NkBQDVqex/UdTvLbzmVI29bThTEGyWzHYtrIjNqM+IJJnqOquXMs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
        const string PRIVATEKEY = "<RSAKeyValue><Modulus>1E1BqQ0uipllOGPMKB4YO/ZutHO0pfQz6jQKFs1y958Vm8YO77APoI65hFYZbFLer3MKx2Obp1Y0DyUyuNIes+IhS7I4nHBS4igdvhohUZDhLLphiuDZ3i5NkBQDVqex/UdTvLbzmVI29bThTEGyWzHYtrIjNqM+IJJnqOquXMs=</Modulus><Exponent>AQAB</Exponent><P>8iXyePGppOkS1hnvMPC5FVfbSDMfSAPfsmXCX3LgoJYxt+n0p1Mm/ZyVnSHm8xJdObGznLRyrVZomuuk6DCyYw==</P><Q>4HI71hZ7VYSWT0ZTehNKvAlhxETWNQlD2YxRwvuHmcVI2+tN7m/RTLkspfXyKsd/opvcqnQeHv2m/LUtiUWEeQ==</Q><DP>UtLH7LY74DwYRUL5nTO5GqPCTR+vQ2KP0OUdZqhUTJkSyGUtWU4HuBcm1WgTJnDRkjpFxQOzdbZocRTIguKlIQ==</DP><DQ>0qJiBUiT9m23oi4dqTLxsAYd+lOfs6Y+RqupD5N+bpD3D2yEdn/5rEcb36Qw4HTZE4GyVUUj/3GMhRyC35CeAQ==</DQ><InverseQ>M1c29WqJO9ET8ymHaBq+Q5gRdpJ79jzV2RlydcMq0dCmHiHjeAwFilVj8AROjvuiOo71fUCleL9+leuOoKgUvg==</InverseQ><D>W14obQX0Ssf7rQoeOgHBskS7nkPRsj5n/VqKIQgoe3NmzFSv5u3hu9rQ8qhPZrQ/jEi5kdhHi/voicAblTkw5rcS7qfamv8NOLz6KV5HwUcyW0eAqL97w7LOJohw7S/3NGblftA76oHGpOpKpZf+u1g7e7w8xRS6RbZ3zqP6yzE=</D></RSAKeyValue>";

        /// 
        /// 加密
        /// 
        /// 待加密的字符串
        ///
        [ThreadStatic]
        private static RSACryptoServiceProvider rsa = null;
        [ThreadStatic]
        private static RSACryptoServiceProvider dersa = null;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        public static string RSAEncryption(string word)
        {
            //CspParameters param = new CspParameters();
            //param.KeyContainerName = PUBLICKEY;

            if (rsa == null)
            {
                rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(PUBLICKEY);
            }
            byte[] plaindata = System.Text.Encoding.Default.GetBytes(word);
            byte[] encryptdata = rsa.Encrypt(plaindata, false);
            string encryptstring = Convert.ToBase64String(encryptdata);
            return encryptstring;
        }


        /// 
        /// 解密,當密文不正確時,可能會拋出異常
        /// 
        /// 待解密的密文字符串
        /// 
        public static string RSADecryption(string encryptWord)
        {
            //CspParameters param = new CspParameters();
            //param.KeyContainerName = PRIVATEKEY;
            if (dersa == null)
            {
                rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(PRIVATEKEY);
            }


            byte[] encryptdata = Convert.FromBase64String(encryptWord);
            byte[] decryptdata = rsa.Decrypt(encryptdata, false);
            string plaindata = System.Text.Encoding.Default.GetString(decryptdata);
            return plaindata;

        }
        #endregion
    }

    /// <summary>
    /// cookie操作
    /// </summary>
    public class CookieExt
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="expires"></param>
        public static void SetCookie(string name, string value, DateTime? expires = null)
        {
            HttpContext.Current.Response.Cookies.Remove(name);
            value = HttpUtility.UrlEncode(value);
            HttpCookie cookie = new HttpCookie(name, value);
            cookie.Domain = FormsAuthentication.CookieDomain;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            if (expires != null)
            {
                cookie.Expires = expires.Value;
            }
            HttpContext.Current.Response.Cookies.Add(cookie);
            //if (HttpContext.Current.Request.Cookies[name] != null)
            //{
            //    HttpContext.Current.Response.Cookies.Set(cookie);
            //}
            //else
            //{
            //    HttpContext.Current.Response.Cookies.Add(cookie);
            //}
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetCookieValueByName(string name)
        {
            string value = HttpContext.Current.Request.Cookies[name].Value;
            value = HttpUtility.UrlDecode(value);
            return value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static HttpCookie GetCookie(string name)
        {
            return HttpContext.Current.Request.Cookies[name];
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        public static void ClearCookie(string name)
        {
            //if (GetCookie(name) != null)
            //{

            //    HttpCookie cookie = GetCookie(name);
            //    cookie.Expires = DateTime.Now.AddDays(-1);

            //    HttpContext.Current.Response.Cookies.Set(cookie);
            //}
            HttpCookie cookie = new HttpCookie(name);
            cookie.Expires = DateTime.Now.AddDays(-1);
            cookie.Path = "/";
            cookie.Domain = FormsAuthentication.CookieDomain;
            HttpContext.Current.Response.Cookies.Add(cookie);
        }


    }

}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved