Example #1
0
 public void Entry()
 {
     var token = "c17e82c72ff74c2ea476006012345678";
     var key   = token.Substring(0, 24);
     var id    = token.Substring(24, 8);
     var s2    = DesEncryptHelper.Decrypt3Des("F+C/TtcK6W4=", key, CipherMode.ECB, id);
 }
Example #2
0
        public async Task <IActionResult> Edit(int id)
        {
            var manager = await _dbContext.managers.FindAsync(id);

            manager.Password = DesEncryptHelper.DesDecrypt(manager.Password);
            if (manager == null)
            {
                return(Redirect("/Home/Index"));
            }
            return(View(manager));
        }
Example #3
0
 public async Task <IActionResult> Edit(Manager manger)
 {
     if (ModelState.IsValid)
     {
         manger.Password = DesEncryptHelper.DesEncrypt(manger.Password);
         _dbContext.Update(manger);
         if (await _dbContext.SaveChangesAsync() > 0)
         {
             return(Json(new { success = true, msg = "修改成功" }));
         }
         return(Json(new { success = false, msg = "修改失败" }));
     }
     return(Json(new { success = false, msg = "提交数据有误,请重新提交" }));
 }
Example #4
0
        /// <summary>
        /// 读取加密cookie
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strName">名称</param>
        /// <param name="cryptType">加密方式</param>
        /// <returns>加密前的对象</returns>
        public static T GetCryptCookie <T>(string strName, CryptType cryptType = CryptType.Aes)
        {
            try
            {
                string jsonString  = null;
                string cryptString = GetCookie(strName);
                #if DEBUG
                jsonString = cryptString;
                if (string.IsNullOrWhiteSpace(jsonString))
                {
                    return(default(T));
                }
                return(JsonConvert.DeserializeObject <T>(jsonString));
                #endif
                switch (cryptType)
                {
                case CryptType.Aes:
                {
                    jsonString = AesEncryptHelper.DecryptAes(cryptString);
                    break;
                }

                case CryptType.Des:
                {
                    jsonString = DesEncryptHelper.DecryptDes(cryptString);
                    break;
                }

                default:
                {
                    jsonString = EncryptUtils.Base64Decrypt(cryptString);
                    break;
                }
                }

                if (string.IsNullOrWhiteSpace(jsonString))
                {
                    return(default(T));
                }
                return(JsonConvert.DeserializeObject <T>(jsonString));
            }
            catch (Exception e)
            {
                LogHelper.Error($@"CookieHelper ReadError {e.Message}", e);
                return(default(T));
            }
        }
Example #5
0
 public JsonResult AddManagers(Manager manager)
 {
     if (ModelState.IsValid)
     {
         //加密
         manager.Password   = DesEncryptHelper.DesEncrypt(manager.Password);
         manager.CreateTime = Convert.ToDateTime(DateTime.Now.ToString());
         manager.IsEnable   = true;
         _dbContext.Add(manager);
         if (_dbContext.SaveChanges() > 0)
         {
             return(Json(new { success = true, msg = "新增成功" }));
         }
         return(Json(new { success = false, msg = "提交失败" }));
     }
     return(Json(new { success = false, msg = "提交数据有误,请重新提交" }));
 }
Example #6
0
 public override void Write(char value)
 {
     try
     {
         var encryptString = DesEncryptHelper.EncryptString(
             string.Join("", value),
             _key
             );
         encryptString = string.Format("{0}{1}{0}\n", "VvvvV", encryptString);
         //将加密串首尾加上"VvvvV"以区分加密串和非加密串混合出现的情况
         base.Write(encryptString);
         Count += this.Encoding.GetByteCount(encryptString);
     }
     catch (Exception e)
     {
         this.ErrorHandler.Error("Failed to write [" + value + "].", e, ErrorCode.WriteFailure);
     }
 }
Example #7
0
        /// <summary>
        /// 添加加密cookie
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strName">名称</param>
        /// <param name="value">需要加密的对象</param>
        /// <param name="expires">过期时间(分钟)</param>
        /// <param name="cryptType">加密方式</param>
        public static void WriteCryptCookie <T>(string strName, T value, int expires = 8 *60, CryptType cryptType = CryptType.Aes)
        {
            string json        = JsonConvert.SerializeObject(value);
            string cryptString = null;

            switch (cryptType)
            {
            case CryptType.Aes:
            {
                cryptString = AesEncryptHelper.EncryptAes(json);

                break;
            }

            case CryptType.Des:
            {
                cryptString = DesEncryptHelper.EncryptDes(json);

                break;
            }

            case CryptType.Sha1:
            {
                cryptString = UnDecryptableEncryptHelpers.Sha1Encrypt(json);
                break;
            }

            case CryptType.Md5:
            {
                cryptString = UnDecryptableEncryptHelpers.Md5Encrypt(json);
                break;
            }

            default:
            {
                cryptString = EncryptUtils.Base64Encrypt(json);
                break;
            }
            }
            #if DEBUG
            cryptString = json;
            #endif
            WriteCookie(strName, cryptString, expires);
        }
Example #8
0
 public override void Write(char[] buffer, int index, int count)
 {
     if (count > 0)
     {
         try
         {
             var encryptString = DesEncryptHelper.EncryptString(
                 string.Join("", buffer.Skip(index).Take(count)),
                 _key
                 );
             encryptString = string.Format("{0}{1}{0}\n", "VvvvV", encryptString);
             //将加密串首尾加上"VvvvV"以区分加密串和非加密串混合出现的情况
             base.Write(encryptString);
             Count += this.Encoding.GetByteCount(encryptString);
         }
         catch (Exception e)
         {
             this.ErrorHandler.Error("Failed to write buffer.", e, ErrorCode.WriteFailure);
         }
     }
 }
Example #9
0
        public CommandResult <object> AddUser(AddUserArgs args)
        {
            try
            {
                //生成密钥,密码
                var timespan = DateTime.Now.ToLongTime().ToString();
                var token    = Guid.NewGuid().ToString().Replace("-", "");
                var key      = token.Substring(0, 24);
                var iv       = timespan.Substring(2, 8);
                args.UserKey  = key + iv;
                args.Password = DesEncryptHelper.Encrypt3Des("123456", key, CipherMode.ECB, iv);

                var result = ContainerFactory <ISqlExcuteContext> .Instance.ExcuteScalarProceDure(0, "add_user", args);

                return(result);
            }
            catch (Exception e)
            {
                LogHelper.Error(this.GetType(), "用户模块-创建用户失败,SchoolId:" + args.SchoolId + ",用户名称:" + args.Name, e);
                return(CommandResult.Failure <object>(e.ToString()));
            }
        }
Example #10
0
        public IActionResult Login(string username, string password)
        {
            var pwd      = DesEncryptHelper.DesEncrypt(password);
            var managers = _dbContext.managers.Where(c => c.Account == username && c.IsEnable == true).ToList();

            if (managers.Count() == 0)
            {
                return(Json(new { success = false, msg = "用户不存在,请联系管理员" }));
            }
            if (!managers.FirstOrDefault().Password.Equals(pwd))
            {
                return(Json(new { success = false, msg = "密码错误,请重新输入" }));
            }
            //登录成功,执行将用户名存储到session  每登录一次记录一次
            var mid = managers.FirstOrDefault().Id;

            //将用户名存储到session
            HttpContext.Session.SetString("username", username);
            HttpContext.Session.SetInt32("mid", mid);
            //将用户ID传给添加登录日志的方法

            AddLoginrecord(mid);
            return(Json(new { success = true, msg = "登录成功" }));


            #region 生成cookie   暂且没用
            //var claimIdentity = new ClaimsIdentity("Cookie", JwtClaimTypes.Name, JwtClaimTypes.Role);
            //claimIdentity.AddClaims(new List<Claim>()
            //    {
            //        new Claim(JwtClaimTypes.Id,managers.FirstOrDefault().Id.ToString()),
            //        new Claim(JwtClaimTypes.Name,managers.FirstOrDefault().Account),
            //        //new Claim(JwtClaimTypes.Email,user.Email)
            //    });

            //var claimPrincipal = new ClaimsPrincipal(claimIdentity);
            //HttpContext.SignInAsync(claimPrincipal);
            #endregion
        }
Example #11
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //权限逻辑
            var  schoolId  = ApplicationContext.SchoolId;
            var  userId    = ApplicationContext.UserId;
            var  roleId    = ApplicationContext.RoleId;
            var  userName  = ApplicationContext.UserName;
            bool isRedirct = schoolId == 0 || userId == 0 || roleId == 0 || string.IsNullOrEmpty(userName);

            if (true)
            {
                //判断cookie中是否包含登陆信息
                bool isRealRedirect = true;
                if (HttpContext.Current.Request.Cookies.AllKeys.Contains("LoginToken") &&
                    HttpContext.Current.Request.Cookies.AllKeys.Contains("UserCookie"))
                {
                    var loginCookie = HttpContext.Current.Request.Cookies["LoginToken"];
                    var userCookie  = HttpContext.Current.Request.Cookies["UserCookie"];

                    if (userCookie != null && loginCookie != null)
                    {
                        var userInfoArray = userCookie.Value.Split('&');
                        if (userInfoArray.Length == 2)
                        {
                            if (int.TryParse(userInfoArray[0], out userId) && int.TryParse(userInfoArray[1], out schoolId))
                            {
                                var userInfos = UserService.Instance.GetUserInfoByUserId(new GetObjectByIdArgs()
                                {
                                    SchoolId = schoolId,
                                    OId      = userId
                                });
                                if (userInfos.Code == 200)
                                {
                                    var user = userInfos.Items.FirstOrDefault();
                                    if (user != null)
                                    {
                                        var userToken = user.Token.Substring(0, 24);
                                        var userIv    = user.Token.Substring(24, 8);
                                        var loginInfo = DesEncryptHelper.Decrypt3Des(loginCookie.Value, userToken, CipherMode.ECB,
                                                                                     userIv);
                                        var loginInfoArray = loginInfo.Split('&');
                                        int roleId2, schoolId2, userId2;
                                        //验证cookie是否造假
                                        if (loginInfoArray.Length == 3 && int.TryParse(loginInfoArray[0], out roleId2) &&
                                            int.TryParse(loginInfoArray[1], out schoolId2) &&
                                            int.TryParse(loginInfoArray[2], out userId2))
                                        {
                                            if (schoolId2 == schoolId && userId2 == userId)
                                            {
                                                ApplicationContext.SchoolId = schoolId;
                                                ApplicationContext.UserId   = userId;
                                                ApplicationContext.RoleId   = roleId2;
                                                ApplicationContext.UserName = user.Name;

                                                //记录登陆信息
                                                var Ip = ApplicationContext.GetHostAddress();
                                                Task.Factory.StartNew(obj =>
                                                {
                                                    var o = (dynamic)obj;
                                                    //存入数据库
                                                    UserService.Instance.AddUserLoginLog(new AddUserLoginLogArgs()
                                                    {
                                                        UserId   = o.UserId,
                                                        SchoolId = o.SchoolId,
                                                        LoginIp  = o.Ip
                                                    });
                                                }, new { Ip, user.UserId, ApplicationContext.SchoolId });

                                                isRealRedirect = false;
                                                base.OnActionExecuting(filterContext);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //是否跳转
                if (isRealRedirect)
                {
                    filterContext.Result = new RedirectToRouteResult("User", new RouteValueDictionary
                    {
                        {
                            "from", HttpContext.Current.Request.Url.ToString()
                        }
                    });
                }
                else
                {
                    base.OnActionExecuting(filterContext);
                }
            }
            else
            {
                base.OnActionExecuting(filterContext);
            }
        }
Example #12
0
        public ActionResult SignIn()
        {
            var from = Request.UrlReferrer != null && Request.UrlReferrer.AbsoluteUri.Contains("from")
                ? Request.UrlReferrer.AbsoluteUri.Substring(Request.UrlReferrer.AbsoluteUri.IndexOf('=') + 1)
                : "";

            try
            {
                if (Request.Cookies.AllKeys.Contains("TOKEN") && Request.Form.AllKeys.Contains("Account") &&
                    Request.Form.AllKeys.Contains("Password"))
                {
                    var accoutS   = Request["Account"];
                    var passwordS = Request["Password"];
                    var key       = Request.Cookies["TOKEN"];
                    var iv        = Request.Cookies["Timespan"];
                    var loginInfo = new LoginUserInfo()
                    {
                        Account  = accoutS,
                        Password = passwordS
                    };
                    if (key != null && iv != null)
                    {
                        var account  = loginInfo.Account;
                        var password = DesEncryptHelper.Decrypt3Des(loginInfo.Password, key.Value, CipherMode.CBC,
                                                                    iv.Value);
                        //获取用户信息
                        var userInfo = UserService.Instance.GetUserInfoByLoginInAccount(new LoginInArgs()
                        {
                            Account = account
                        });
                        if (userInfo.Code == 200)
                        {
                            var user = userInfo.Items.FirstOrDefault();
                            if (user != null)
                            {
                                //通过用户的token解密用户密码,然后跟此次输入密码比对
                                var userToken    = user.Token.Substring(0, 24);
                                var userIv       = user.Token.Substring(24, 8);
                                var userPassword = DesEncryptHelper.Decrypt3Des(user.Password, userToken, CipherMode.ECB,
                                                                                userIv);
                                if (userPassword == password)
                                {
                                    ApplicationContext.RoleId   = user.RoleId;
                                    ApplicationContext.SchoolId = user.SchoolId;
                                    ApplicationContext.UserId   = user.UserId;
                                    ApplicationContext.UserName = user.Name;
                                    var Ip = ApplicationContext.GetHostAddress();
                                    //登陆信息是否记录cookie中
                                    if (Request.Form.AllKeys.Contains("ckRemeber"))
                                    {
                                        var ck = Request["ckRemeber"];
                                        if (ck == "None")
                                        {
                                            var login      = user.RoleId + "&" + user.SchoolId + "&" + user.UserId;
                                            var loginToken = DesEncryptHelper.Encrypt3Des(login, userToken,
                                                                                          CipherMode.ECB, userIv);
                                            //存储登陆信息到cookie中
                                            HttpCookie loginCookie = new HttpCookie("LoginToken", loginToken);
                                            loginCookie.Expires = DateTime.Now.AddDays(1);
                                            Response.Cookies.Add(loginCookie);
                                            //存储userid、schoolid到cookie中
                                            var        userSchool = user.UserId + "&" + user.SchoolId;
                                            HttpCookie userCookie = new HttpCookie("UserCookie", userSchool);
                                            loginCookie.Expires = DateTime.Now.AddDays(1);
                                            Response.Cookies.Add(userCookie);
                                        }
                                    }

                                    //记录登陆信息
                                    Task.Factory.StartNew(obj =>
                                    {
                                        var o = (dynamic)obj;
                                        //存入数据库
                                        UserService.Instance.AddUserLoginLog(new AddUserLoginLogArgs()
                                        {
                                            UserId   = o.UserId,
                                            SchoolId = o.SchoolId,
                                            LoginIp  = o.Ip
                                        });
                                    }, new { Ip, user.UserId, user.SchoolId });

                                    if (!string.IsNullOrEmpty(from))
                                    {
                                        return(Redirect(HttpUtility.UrlDecode(from)));
                                    }
                                    return(RedirectToAction("Index", "Home"));
                                }
                                ViewBag.Msg = "用户密码错误";
                            }
                            else
                            {
                                ViewBag.Msg = "用户不存在";
                            }
                        }
                        else
                        {
                            ViewBag.Msg = "服务器异常,请稍后重试";
                        }
                    }
                    else
                    {
                        ViewBag.Msg = "页面数据异常,请刷新页面";
                    }
                }
                else
                {
                    ViewBag.Msg = "令牌格式错误";
                }

                SetToken();
                return(View("Login"));
            }
            catch (Exception e)
            {
                LogHelper.Error(this.GetType(), e.ToString(), e);
                ViewBag.Msg = "用户登录异常";
                SetToken();
                return(View("Login"));
            }
        }
Example #13
0
        public string ChangePassword(PasswordInfo passwordInfo)
        {
            try
            {
                var userId   = ApplicationContext.UserId;
                var schoolId = ApplicationContext.SchoolId;
                if (passwordInfo != null && Request.Cookies.AllKeys.Contains("TOKEN"))
                {
                    var key = Request.Cookies["TOKEN"];
                    var iv  = Request.Cookies["Timespan"];
                    if (key != null && iv != null)
                    {
                        //先解密码,然后比对系统中的密码
                        var originalPassword = DesEncryptHelper.Decrypt3Des(passwordInfo.OriginalPassword, key.Value,
                                                                            CipherMode.CBC,
                                                                            iv.Value);
                        var newPassword = DesEncryptHelper.Decrypt3Des(passwordInfo.NewPassword, key.Value,
                                                                       CipherMode.CBC,
                                                                       iv.Value);

                        var userInfo = UserService.Instance.GetUserInfoByUserId(new GetObjectByIdArgs()
                        {
                            OId      = userId,
                            SchoolId = schoolId
                        });

                        if (userInfo.Code == 200)
                        {
                            var user = userInfo.Items.FirstOrDefault();
                            if (user != null)
                            {
                                //通过用户的token解密用户密码,然后跟此次输入密码比对
                                var userToken    = user.Token.Substring(0, 24);
                                var userIv       = user.Token.Substring(24, 8);
                                var userPassword = DesEncryptHelper.Decrypt3Des(user.Password, userToken,
                                                                                CipherMode.ECB,
                                                                                userIv);
                                //对比原始密码
                                if (userPassword == originalPassword)
                                {
                                    //开始修改密码
                                    var newPasswordEncrypt = DesEncryptHelper.Encrypt3Des(newPassword, userToken,
                                                                                          CipherMode.ECB, userIv);
                                    var result = UserService.Instance.UpdateUserPassword(new UpdatePasswordArgs()
                                    {
                                        ModifyBy = userId,
                                        SchoolId = schoolId,
                                        Password = newPasswordEncrypt,
                                        UserId   = userId
                                    });
                                    return(JsonHelper.Serialize(result));
                                }
                                return(JsonHelper.Serialize(CommandResult.Failure("原始密码错误")));
                            }
                            return(JsonHelper.Serialize(CommandResult.Failure("用户不存在")));
                        }
                        return(JsonHelper.Serialize(CommandResult.Failure("服务器异常,请稍后重试")));
                    }
                }
                return(JsonHelper.Serialize(CommandResult.Failure("页面数据异常,请刷新页面")));
            }
            catch (Exception e)
            {
                return(JsonHelper.Serialize(CommandResult.Failure("服务器异常:" + e.ToString())));
            }
        }