• 单点登陆


    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);
            }
    
    
        }
    
    }

    需要整理,我只是开发的原稿弄出来了!有很多没用的!

  • 相关阅读:
    (转)C#中的那些全局异常捕获
    mysql 5.7 MGR
    mysql 5.7 MGR
    perl 获取响应头
    python 获取响应头
    研究生开咖啡厅,年盈利15万,欲打造重庆咖啡文化
    女学生经营二手服装租赁,年营业额突破300万
    在校学生看中餐饮外送行业,企业估值500亿
    导演跨界跳入椰子水“新泳池”,一举占领椰子产品市场
    在校女学生,掌管27家卤味连锁店
  • 原文地址:https://www.cnblogs.com/jiangu66/p/3174320.html
Copyright © 2020-2023  润新知