コード例 #1
0
        public JsonResult RestPassword(int id, string newPassword)
        {
            Random rn   = new Random();
            string salt = rn.Next(10000, 99999).ToString() + rn.Next(10000, 99999).ToString();

            EnterRepository.GetRepositoryEnter().GetAdminRepository.EditEntity(new Model.Admin()
            {
                Id = id, Password = MD5Helper.CreatePasswordMd5(newPassword, salt), Salt = salt
            }, new string[] { "Password", "Salt" });
            PublicFunction.AddOperation(1, string.Format("重置管理员密码"), string.Format("重置管理员=={0}==密码成功", id));
            if (EnterRepository.GetRepositoryEnter().SaveChange() > 0)
            {
                return(Json(new { state = "success", message = "重置管理员密码成功" }));
            }
            else
            {
                PublicFunction.AddOperation(1, string.Format("重置管理员密码"), string.Format("修改管理员=={0}==可登陆状态失败", id));
                EnterRepository.GetRepositoryEnter().SaveChange();
                return(Json(new { state = "error", message = "服务器泡妞去了" }));
            }
        }
コード例 #2
0
 public bool ResetPassword(decimal userId, string newPassword)
 {
     try
     {
         var sql       = "USER_ResetPassword";
         var sqlParams = new[]
         {
             new SqlParameter("p_user_id", SqlDbType.Int),
             new SqlParameter("p_new_password", SqlDbType.VarChar)
         };
         sqlParams[0].Value = userId;
         sqlParams[1].Value = MD5Helper.GetMd5(newPassword);
         var dt = db.ExecuteDataTable(CommandType.StoredProcedure, sql, sqlParams);
         return(true);
     }
     catch (Exception ex)
     {
         NLogHelper.Logger.Error(string.Format("ResetPassword: {0}", ex.ToString()));
         return(false);
     }
 }
コード例 #3
0
ファイル: HystrixAOP.cs プロジェクト: yunqian007/Consul
        /// <summary>
        /// object 转 string
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        protected static string GetArgumentValue(object arg)
        {
            if (arg is DateTime || arg is DateTime?)
            {
                return(((DateTime)arg).ToString("yyyyMMddHHmmss"));
            }

            if (arg is string || arg is ValueType || arg is Nullable)
            {
                return(arg.ToString());
            }

            if (arg != null)
            {
                if (arg.GetType().IsClass)
                {
                    return(MD5Helper.MD5Encrypt16(Newtonsoft.Json.JsonConvert.SerializeObject(arg)));
                }
            }
            return(string.Empty);
        }
コード例 #4
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="userName"></param>
 /// <param name="password"></param>
 /// <param name="ip"></param>
 /// <returns></returns>
 public DataTable Login(string userName, string password)
 {
     try
     {
         var sql       = "CMS_USER_LOGIN";
         var sqlParams = new[]
         {
             new SqlParameter("p_username", SqlDbType.VarChar),
             new SqlParameter("p_password", SqlDbType.VarChar)
         };
         sqlParams[0].Value = userName;
         sqlParams[1].Value = MD5Helper.GetMd5(password);
         var dt = db.ExecuteDataTable(CommandType.StoredProcedure, sql, sqlParams);
         return(dt);
     }
     catch (Exception ex)
     {
         NLogHelper.Logger.Error(string.Format("Login: {0}", ex.ToString()));
         return(null);
     }
 }
コード例 #5
0
        private void RequestCallback(IAsyncResult asyncResult)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            string       pars     = "UserName="******"&PassWord="******"&UserMail=" + _registerInfo.UserMail;

            Random random       = new Random();
            int    randomNumber = random.Next(999999);
            string randomKey    = string.Format("{0:D6}", random);
            string validateStr  = _registerInfo.PassWord + randomKey + (_registerInfo.UserMail.StartsWith("@") ? "" : _registerInfo.UserMail) + "" + _registerInfo.UserName;
            string md5Validate  = MD5Helper.GetMd5String(validateStr).Substring(13, 10).ToLower();

            pars += "&RandomKey=" + randomKey + "&ValidateKey=" + md5Validate + "&ReturnURL=" + "";

            Stream _body = _httpWebRequest.EndGetRequestStream(asyncResult);

            byte[] formBytes = encoding.GetBytes(pars);
            _body.Write(formBytes, 0, formBytes.Length);
            _body.Close();

            _httpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), _requestState);
        }
コード例 #6
0
        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="mi">ManagerInfo类型的对象</param>
        /// <returns>受影响的行数</returns>
        public int Update(ManagerInfo mi)
        {
            //定义参数集合,可以动态添加元素
            List <SQLiteParameter> listPs = new List <SQLiteParameter>();
            //构造update的sql语句
            string sql = "UPDATE ManagerInfo SET MName = @name,";

            listPs.Add(new SQLiteParameter("@name", mi.MName));
            //判断是否修改密码
            if (!mi.MPwd.Equals("这是原来的密码吗?"))
            {
                sql += " MPwd = @pwd,";
                listPs.Add(new SQLiteParameter("@pwd", MD5Helper.EncrytString(mi.MPwd)));
            }
            //继续拼接sql语句
            sql += " MType = @type WHERE MId =@id";
            listPs.Add(new SQLiteParameter("@id", mi.MId));
            listPs.Add(new SQLiteParameter("@type", mi.MType));
            //执行语句并返回结果
            return(SqliteHelper.ExecuteNonQuery(sql, listPs.ToArray()));//ToArray将集合转化成数组
        }
コード例 #7
0
ファイル: WeChatAPI.cs プロジェクト: guiyuhao111/baseStudy
        /// <summary>
        /// 发送消息给微信公众平台接口
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="openID"></param>
        /// <returns></returns>
        private static string SignMsg(string title, string content, string openID)
        {
            string param = "description=" + content + "&openId=" + openID + "&title=" + title;

            string[] msg      = { "description" + HttpUtility.UrlEncode(content, Encoding.UTF8), "openId" + HttpUtility.UrlEncode(openID, Encoding.UTF8), "title" + HttpUtility.UrlEncode(title, Encoding.UTF8), KeyHelper.wechatMD5Key };
            string[] msg_sort = BubbleSort(msg);
            string   postMsg  = string.Empty;

            foreach (var item in msg_sort)
            {
                postMsg += item;
            }
            string sign = new MD5Helper(string.Empty).Encrypt(postMsg);

            param = param + "&sign=" + sign;
            try
            {
                return(ToolHelper.Post("http://wechat.51ipc.com/sendCustomMsg", param));
            }
            catch { return(string.Empty); }
        }
コード例 #8
0
        public async Task <IActionResult> PostUser([FromBody] User user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (_context.User.FirstOrDefault(x => x.Email == user.Email) != null)
            {
                return(BadRequest("Email already exist"));
            }

            var passwordHashed = MD5Helper.Encode(user.Password);

            user.Password = passwordHashed;

            _context.User.Add(user);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetUser", new { id = user.IdUser }, user));
        }
コード例 #9
0
ファイル: ManagerInfoDal.cs プロジェクト: Susilen/Cater
        public int Update(ManagerInfo mi)
        {
            var list = new List <SQLiteParameter>();

            var sql = "update managerinfo set mname=@name,";

            list.Add(new SQLiteParameter("@name", mi.MName));

            //判断要不要改密码
            if (!mi.MPwd.Equals("******"))
            {
                sql += "mpwd=@pwd,";
                list.Add(new SQLiteParameter("@pwd", MD5Helper.GetMD5(mi.MPwd)));
            }

            sql += "mtype = @type where mid = @id";
            list.Add(new SQLiteParameter("@id", mi.Mid));
            list.Add(new SQLiteParameter("@type", mi.MType));

            return(SqliteHelper.ExecuteNonQuery(sql, list.ToArray()));
        }
コード例 #10
0
        public async Task <IActionResult> Login([FromBody] RequestUser model)
        {
            var pwd   = MD5Helper.MD5Encrypt32(model.password);
            var query = await _baseUser.Query(f => f.username.Equals(model.username) && f.password.Equals(pwd) && f.status == 1);

            if (query.Count == 0)
            {
                throw new BadExceptionResult("User is valid!");
            }
            var bytes = SerializeHelper.SerializeToBytes(query);

            //TODO根据项目获取数据库
            _redisManager.SetDefaultDatabase(12);
            _redisManager.SetHash(RedisConstant.UserData, query.First().id.ToStr(), bytes);
            var token = "bearer ";

            token += JwtHelper.IssueJwt(new JwtTokenModel {
                Role = "admin,test", Uid = 1
            });
            return(new ObjectResult(new { token }));
        }
コード例 #11
0
        public ActionResult ChangePass(string userNameChange, string newPass)
        {
            var Md5pass = MD5Helper.MD5Encrypt(newPass);

            try
            {
                using (var userDal = new UserDAL())
                {
                    var AccountInfo = userDal.GetUserByUserNameOrEmail(userNameChange);
                    AccountInfo.UserPassword = Md5pass;
                    userDal.UpdateUser(AccountInfo);
                }
                FormsAuthentication.SignOut();
                return(Redirect("/#/Login"));
            }
            catch (Exception ex)
            {
                //ViewBag.ErrorMessage = ex;
                return(Redirect("/#/Error"));
            }
        }
コード例 #12
0
    private void ExportAll(string exportDir)
    {
        string md5File = Path.Combine(ExcelPath, "md5.txt");

        if (!File.Exists(md5File))
        {
            this.md5Info = new ExcelMD5Info();
        }
        else
        {
            this.md5Info = MongoHelper.FromJson <ExcelMD5Info>(File.ReadAllText(md5File));
        }

        foreach (string filePath in Directory.GetFiles(ExcelPath))
        {
            if (Path.GetExtension(filePath) != ".xlsx")
            {
                continue;
            }
            if (Path.GetFileName(filePath).StartsWith("~"))
            {
                continue;
            }
            string fileName = Path.GetFileName(filePath);
            string oldMD5   = this.md5Info.Get(fileName);
            string md5      = MD5Helper.FileMD5(filePath);
            this.md5Info.Add(fileName, md5);
            if (md5 == oldMD5)
            {
                continue;
            }

            Export(filePath, exportDir);
        }

        File.WriteAllText(md5File, this.md5Info.ToJson());

        Log.Info("所有表导表完成");
        AssetDatabase.Refresh();
    }
コード例 #13
0
        public static (Message Message, byte[] Content) Send(string server, string username, string password,
                                                             object message, Command command, string name)
        {
            TcpClient     client = null;
            NetworkStream stream = null;

            try
            {
                var data = EncryptMessage(username, password, command, message);
                // TODO: Parse ip adress better
                client = new TcpClient(server.Split(":")[0], int.Parse(server.Split(":")[1]));
                stream = client.GetStream();

                stream.Write(data, 0, data.Length);
                stream.Flush();
                data = new byte[256];
                stream.Read(data, 0, data.Length);

                var returnData = MessagePackSerializer.Deserialize <Message>(data);
                return(
                    returnData,
                    RijndaelManager.Decrypt(returnData.Content, MD5Helper.CalculateMD5Hash(password))
                    );
            }
            catch (ArgumentNullException e)
            {
                Error($"ArgumentNullException: {e}", name);
                throw;
            }
            catch (SocketException e)
            {
                Error($"SocketException: {e}", name);
                throw;
            }
            finally
            {
                stream?.Close();
                client?.Close();
            }
        }
コード例 #14
0
        public ActionResult verification(string action, string pwd, string userid, string remember_me)
        {
            var id2   = Session.SessionID;
            var model = accountService.GetLoginModel(userid);

            if (model != null)
            {
                if (model.userpwd.ToLower() == MD5Helper.MD5_32(pwd).ToLower())
                {
                    model.login_time     = DateTime.Now;
                    Session["LoginUser"] = model;
                    var sid       = SessionHelper.SessionId;
                    var functions = accountService.GetMyFunctionString(Masterpage.CurrUser.role_sn);
                    Session["MyFunctionString"] = functions;
                    if (remember_me != null && remember_me == "on")
                    {
                        CookieHelper.SetCookie("remember_me", remember_me, DateTime.Now.AddMonths(1));
                        CookieHelper.SetCookie("remember_userid", userid, DateTime.Now.AddMonths(1));
                    }
                    else
                    {
                        CookieHelper.ClearCookie("remember_userid");
                        CookieHelper.ClearCookie("remember_me");
                    }
                    return(Redirect("../main/index"));
                }
                else
                {
                    return(RedirectToAction(action, new { url = "", v1 = "", v2 = "密码输入错误" }));
                    //back = new ReturnValue { status = false, value2 = "密码输入错误" };
                }
            }
            else
            {
                return(RedirectToAction(action, new { url = "", v1 = "用户名不存在", v2 = "" }));
                //return View("login", new { url = "", v1 = "用户名不存在", v2 = "" });
                //back = new ReturnValue { status = false,value="用户名不存在" };
            }
            //return Json(back, JsonRequestBehavior.AllowGet);
        }
コード例 #15
0
        public ActionResult LoginUser()
        {
            string sessionValidateCode = Session["ValidateCode"] != null ? Session["ValidateCode"].ToString() : string.Empty;

            if (string.IsNullOrEmpty(sessionValidateCode))
            {
                return(Content("N:验证码错误!"));
            }
            if (!Request["vCode"].Equals(sessionValidateCode, StringComparison.CurrentCultureIgnoreCase))
            {
                return(Content("N:验证码错误!"));
            }

            string uName     = Request["LoginCode"];
            string uPwd      = Request["LoginPwd"];
            var    loginUser = UserInfoService.LoadEntities(u => u.UName == uName && u.UPwd == uPwd).FirstOrDefault();

            if (loginUser == null)
            {
                Session["ValidateCode"] = null;
                return(Content("N:用户名密码错误!"));
            }
            //  Session["LoginUser"] = loginUser;
            else
            {
                string sessionCookie = Guid.NewGuid().ToString();
                MemcachedHelper.SetMemcachedData(sessionCookie, JsonSerializeHelper.JsonSerialize(loginUser), DateTime.Now.AddMinutes(20));
                Response.Cookies["LoginCookie"].Value = sessionCookie;
            }
            if (Request["checkRemember"] != null)
            {
                HttpCookie cp1 = new HttpCookie("UName", loginUser.UName);
                HttpCookie cp2 = new HttpCookie("UPwd", MD5Helper.GetMD5String(MD5Helper.GetMD5String(loginUser.UPwd)));
                cp1.Expires = DateTime.Now.AddDays(5);
                cp2.Expires = DateTime.Now.AddDays(5);
                HttpContext.Response.Cookies.Add(cp1);
                HttpContext.Response.Cookies.Add(cp2);
            }
            return(Content("Y:用户登陆成功!"));
        }
コード例 #16
0
        private void btnDoiMatKhau_Click(object sender, EventArgs e)
        {
            if (txtMatKhauCu.Text == "")
            {
                MessageBox.Show("Mật khẩu cũ không được để trống", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string matkhaucu = txtMatKhauCu.Text;

            if (MD5Helper.GetMD5HashValue(matkhaucu) != ThamSoHeThong.curTaikhoan.PASSWORDMD5)
            {
                MessageBox.Show("Mật khẩu cũ không chính xác", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (txtMatKhauMoi.Text == "")
            {
                MessageBox.Show("Mật khẩu mới không được để trống", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (txtMatKhauMoi.Text != txtXacNhan.Text)
            {
                MessageBox.Show("Xác nhận mật khẩu không chính xác", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            ThamSoHeThong.curTaikhoan.PASSWORDMD5 = MD5Helper.GetMD5HashValue(txtMatKhauMoi.Text);
            if (TAIKHOANService.Update(ThamSoHeThong.curTaikhoan))
            {
                MessageBox.Show("Đổi mật khẩu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Đổi mật khẩu thất bại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            this.Close();
        }
コード例 #17
0
ファイル: ManagerinfoDal.cs プロジェクト: AlexHung123/Cater
        public List <Managerinfo> GetList(Managerinfo mi)
        {
            //构造sql语句
            string sql = "select * from Managerinfo";
            //拼接查询,得到结果
            List <SQLiteParameter> listP = new List <SQLiteParameter>();

            if (mi != null)
            {
                sql += " where mname=@name and mpwd=@pwd";
                listP.Add(new SQLiteParameter("@name", mi.MName));
                listP.Add(new SQLiteParameter("@pwd", MD5Helper.GetMd5(mi.MPwd)));
            }


            //执行查询,获取数据
            DataTable table = SqliteHelper.GetList(sql, listP.ToArray());


            //构造集合对象
            //定义一个集合用于转存数据
            List <Managerinfo> list = new List <Managerinfo>();

            //逐行遍历数据,将表中的数据存到集合中
            foreach (DataRow row in table.Rows)
            {
                //1.list.Add()
                //2.new Managerinfo()
                //3.对象的初始化
                list.Add(new Managerinfo()
                {
                    MId   = Convert.ToInt32(row["mid"]),
                    MName = row["mname"].ToString(),
                    MPwd  = row["mpwd"].ToString(),
                    MType = Convert.ToInt32(row["mtype"])
                });
            }
            //返回数据
            return(list);
        }
コード例 #18
0
        public LoginState Login(string name, string pwd, out int type)
        {
            type = -1;
            ManagerInfo mi = miDal.GetByName(name);

            if (mi == null)
            {
                return(LoginState.NameERROR);
            }
            else
            {
                if (mi.MPwd.Equals(MD5Helper.GetMD5String(pwd)))
                {
                    type = mi.MType;
                    return(LoginState.Ok);
                }
                else
                {
                    return(LoginState.PwdERROR);
                }
            }
        }
コード例 #19
0
ファイル: UserInfoService.cs プロジェクト: hanlei520/ZDNL
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="model"></param>
        /// <param name="UserID"></param>
        /// <param name="NewPwd"></param>
        /// <param name="Pwd"></param>
        /// <returns></returns>
        public bool ResetPwd(string PassWord, string UserID, string NewPwd, string Pwd)
        {
            //先查
            UserInfo entity = userInfoDAL.LoadEntities(u => u.UserID == UserID).FirstOrDefault();

            if (entity != null)
            {
                if (PassWord != null)
                {
                    string strPassWord = MD5Helper.EncryptString(PassWord);
                    if (entity.PassWord != strPassWord)
                    {
                        return(false);
                    }
                    if (NewPwd != Pwd)
                    {
                        return(false);
                    }
                    Pwd             = MD5Helper.EncryptString(Pwd);
                    entity.PassWord = Pwd;
                    if (userInfoDAL.EditAndSaveChange(entity) > 0)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
コード例 #20
0
        public bool Login(string pwd)
        {
            var wallet = WalletDao.GetActiveWallet();

            if (MD5Helper.ToMD5(pwd) != wallet.Password)
            {
                return(false);
            }

            var mnemonicWords = CryptHelper.AESDecryptText(wallet.MnemonicWords, pwd);
            var result        = KeyOperator.Instance.Recover(pwd, mnemonicWords);

            GlobalWallet.Set(new ActiveWallet
            {
                Id           = wallet.Id,
                Name         = wallet.WalletName,
                RootXPrivKey = result.RootExtPrivKeyWif,
                RootXPubKey  = result.RootExtPubKeyWif
            });

            return(true);
        }
コード例 #21
0
        public async Task <IActionResult> GetGravatarImage()
        {
            await Task.FromResult(0);

            string gravatarUrl = "";
            string userEmail   = this.GetUserEmail();

            using (MD5 md5Hash = MD5.Create())
            {
                string hash = MD5Helper.GetMd5Hash(md5Hash, userEmail);
                if (MD5Helper.VerifyMd5Hash(md5Hash, userEmail, hash))
                {
                    gravatarUrl = "{'gravtarUrl': 'https://gravatar.com/avatar/" + hash + "?d=404'}";
                    JObject jObj = JObject.Parse(gravatarUrl);
                    return(Json(jObj));
                }
                else
                {
                    return(BadRequest());
                }
            }
        }
コード例 #22
0
        public ActionResult Login(LoginModel model)
        {
            using (var db = new ExchangedbEntities())
            {
                if (ModelState.IsValid)
                {
                    var dbUser = db.Users.FirstOrDefault(a => a.Login.Equals(model.Login)) ??
                                 db.Users.FirstOrDefault(a => a.Address.Email.Equals(model.Login));

                    if (dbUser != null)
                    {
                        if (dbUser.Password == MD5Helper.GetHashString(model.Password) &&
                            dbUser.ConfirmEmail)
                        {
                            Session["Id"]         = dbUser.Id.ToString();
                            Session["Login"]      = dbUser.Login;
                            Session["UserTypeId"] = dbUser.UserTypeId;
                            return(RedirectToAction("HomePage", "Home"));
                            //return RedirectToAction("HomePage", "Home", new { userId = dbUser.Id});
                        }
                        if (!dbUser.ConfirmEmail)
                        {
                            ModelState.AddModelError("", "Email is not confirmed");
                        }
                        ModelState.AddModelError("", "Wrong password");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Wrong login");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Wrong input");
                }

                return(View(model));
            }
        }
コード例 #23
0
        public async Task <IActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(RedirectToAction(nameof(ResetPasswordConfirmation)));
            }


            // 防止篡改
            var getAccessCode = MD5Helper.MD5Encrypt32(model.userId + model.Code);

            if (getAccessCode != model.AccessCode)
            {
                return(RedirectToAction(nameof(AccessDenied), new { errorMsg = "随机码已被篡改!密码重置失败!" }));
            }

            if (user != null && user.Id.ToString() != model.userId)
            {
                return(RedirectToAction(nameof(AccessDenied), new { errorMsg = "不能修改他人邮箱!密码重置失败!" }));
            }


            var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);

            if (result.Succeeded)
            {
                return(RedirectToAction(nameof(ResetPasswordConfirmation)));
            }
            AddErrors(result);
            return(View());
        }
コード例 #24
0
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }
            using (var db = new ExchangedbEntities())
            {
                var id     = Session["Id"].ToString();
                var dbUser = db.Users.FirstOrDefault(a => a.Id.ToString().Equals(id));

                if (MD5Helper.GetHashString(model.OldPassword) != dbUser.Password)
                {
                    ModelState.AddModelError("", "Wrong old password");
                    return(View());
                }

                dbUser.Password = MD5Helper.GetHashString(model.NewPassword);
                db.SaveChanges();
            }
            return(RedirectToAction("HomePage", "Home"));
        }
コード例 #25
0
        public async Task Invoke(HttpContext context)
        {
            var route = context.Request.Path.Value;

            if (!route.Equals("/authentication") && !route.Equals("/") && !route.Equals("/favicon.ico"))
            {
                var token = context.Request.Headers["Authorization"];

                if (String.IsNullOrEmpty(token))
                {
                    var response = context.Response;
                    response.ContentType = "text/plain; charset=utf-8";
                    response.StatusCode  = 401;

                    await response.WriteAsync("Token de acesso não informado.");
                }
                else
                {
                    var userCode = MD5Helper.Uncrypt(token);

                    if (!_service.IsAuth(userCode, route))
                    {
                        var response = context.Response;
                        response.ContentType = "text/plain; charset=utf-8";
                        response.StatusCode  = 401;

                        await response.WriteAsync("Usuário não possui acesso.");
                    }
                    else
                    {
                        await _next(context);
                    }
                }
            }
            else
            {
                await _next(context);
            }
        }
コード例 #26
0
        /// <summary>
        /// object 转 string
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        protected static string GetArgumentValue(object arg)
        {
            if (arg is DateTime || arg is DateTime?)
            {
                return(((DateTime)arg).ToString("yyyyMMddHHmmss"));
            }

            if (!arg.IsNotEmptyOrNull())
            {
                return(arg.ObjToString());
            }

            if (arg != null)
            {
                if (arg.GetType().IsClass)
                {
                    return(MD5Helper.MD5Encrypt16(JsonConvert.SerializeObject(arg)));
                }
                return($"value:{arg.ObjToString()}");
            }
            return(string.Empty);
        }
コード例 #27
0
        /// <summary>
        /// Аутендификация пользователя
        /// </summary>
        /// <param name="username">Логин/Email/Телефон</param>
        /// <param name="password">Пароль</param>
        /// <returns></returns>
        private async Task <ClaimsIdentity> GetIdentity(string username, string password)
        {
            var  paswordHash = MD5Helper.GetMD5Hash(password);
            User user        = await _userRepository.FirstOrDefault(x => (x.Email == username || x.Nickname == username || x.PhoneNumber == username) &&
                                                                    x.PasswordHash == paswordHash);

            if (user != null)
            {
                var claims = new List <Claim>
                {
                    new Claim("Email", user.Email),
                    new Claim("Id", user.Id.ToString()),
                };
                ClaimsIdentity claimsIdentity =
                    new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType,
                                       ClaimsIdentity.DefaultRoleClaimType);
                return(claimsIdentity);
            }

            // если пользователя не найдено
            return(null);
        }
コード例 #28
0
        private static void GenerateVersionProto(string dir, VersionConfig versionProto, string relativePath, bool pIsAbSec)
        {
            foreach (string file in Directory.GetFiles(dir))
            {
                string   md5      = MD5Helper.FileMD5(file);
                FileInfo fi       = new FileInfo(file);
                long     size     = fi.Length;
                string   filePath = relativePath == "" ? fi.Name : $"{relativePath}/{fi.Name}";

                versionProto.FileInfoDict.Add(filePath, new FileVersionInfo
                {
                    File = filePath,
                    MD5  = md5,
                    Size = size,
                });
            }
            foreach (string directory in Directory.GetDirectories(dir))
            {
                DirectoryInfo dinfo = new DirectoryInfo(directory);
                string        rel   = relativePath == "" ? dinfo.Name : $"{relativePath}/{dinfo.Name}";
                GenerateVersionProto($"{dir}/{dinfo.Name}", versionProto, rel, pIsAbSec);
            }
            string tDayHour = DateTime.Now.ToString("yyMMddHHmm");

            versionProto.Version    = int.Parse(tDayHour);
            versionProto.ABSecurity = pIsAbSec ? 2 : 1;//0未知,去load下, 1不使用加密   ,2加密-------若0使用不加密
            #region MyRegion
            //try
            //{//加密时,把version.txt删除了,无法记录第几次,只能使用时间记录了
            //    var oldConfig = JsonHelper.FromJson<VersionConfig>(File.ReadAllText($"{dir}/Version.txt"));
            //    var oldver = oldConfig.Version.ToString().Substring(6, 4);
            //    versionProto.Version = int.Parse(tDay + oldver) + 1;
            //}
            //catch (Exception)
            //{
            //    versionProto.Version = int.Parse(tDay + "1000");
            //}
            #endregion
        }
コード例 #29
0
ファイル: YXSV.cs プロジェクト: GSIL-Monitor/BTP
        static string GenerateParameter(string method, Dictionary <string, string> paras)
        {
            Dictionary <string, string> dic = new Dictionary <string, string>();

            dic.Add("appKey", AppKey);
            dic.Add("method", method);
            dic.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            paras.ToList().ForEach(x =>
            {
                dic.Add(x.Key, string.IsNullOrEmpty(x.Value) ? x.Value : x.Value.Replace("+", " ").Replace("%", " "));
            });
            dic = dic.OrderBy(_ => _.Key).ToDictionary(_ => _.Key, _ => _.Value);

            //参数值拼接的字符串收尾添加appSecret值
            var waitSignStr = AppSecret + string.Join("", dic.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value))) + AppSecret;

            LogHelper.Debug("YXSV.GenerateParameter 计算sign前 waitSignStr=" + waitSignStr);

            dic.Add("sign", MD5Helper.GetMD5(waitSignStr, Encoding.UTF8).ToUpper());

            return(string.Join("&", dic.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value))));
        }
コード例 #30
0
        /// <summary>
        /// Validates the request message content header, <c>ContentMD5</c>, matches a newly calculated MD5 hash of the content.
        /// </summary>
        /// <param name="requestMessage">The request message to have its content validated.</param>
        /// <returns><c>true</c> if the MD5 hash of the request content matches the <c>ContentMD5</c> content header; <c>false</c> otherwise.</returns>
        private async Task <bool> IsMd5Valid(HttpRequestMessage requestMessage)
        {
            var content          = requestMessage.Content;
            var contentMD5Header = requestMessage.Content?.Headers?.ContentMD5;

            // Validate that if there is no content then the there is also no ContentMD5 header (i.e. message body wasn't removed).
            if (content == null || content.Headers.ContentLength == 0)
            {
                return((contentMD5Header == null) || (contentMD5Header.Length == 0));
            }

            // Validate that if there is content then there is also a ContentMD5 header (i.e. contentMD5 header wasn't removed or left out).
            else if ((content.Headers.ContentLength > 0) && ((contentMD5Header == null) || (contentMD5Header.Length == 0)))
            {
                return(false);
            }

            // Validate the ContentMD5 header matches our calculated hash.
            var hash = await MD5Helper.ComputeHash(content);

            return(hash.SequenceEqual(contentMD5Header));
        }
コード例 #31
0
ファイル: Program.cs プロジェクト: hardborn/MonitorManager
 private static bool CheckUpdatePackageMD5(string filePath, string md5Code, out MD5Helper.FileMD5ErrorMode errCode)
 {
     string currentMD5Code;
     errCode = MD5Helper.CreateMD5(filePath, out currentMD5Code);
     if (errCode != MD5Helper.FileMD5ErrorMode.OK)
     {
         System.Console.WriteLine("Calculation file md5 error,Err:" + errCode.ToString());
         try
         {
             File.Delete(filePath);
         }
         catch { }
         return false;
     }
     if (md5Code.ToLower() != currentMD5Code.ToLower())
     {
         System.Console.WriteLine("File md5 is not match!");
         try
         {
             File.Delete(filePath);
         }
         catch { }
         return false;
     }
     else return true;
 }
コード例 #32
0
ファイル: Program.cs プロジェクト: hardborn/MonitorManager
 /// <summary>
 /// 校验更新包MD5码
 /// </summary>
 /// <param name="filePath"></param>
 /// <param name="md5Code"></param>
 /// <param name="errCode"></param>
 /// <returns>是否校验成功</returns>
 private static bool FileMD5Check(string filePath, string md5Code, out MD5Helper.FileMD5ErrorMode errCode)
 {
     string currentMD5Code;
     errCode = MD5Helper.CreateMD5(filePath, out currentMD5Code);
     if (errCode != MD5Helper.FileMD5ErrorMode.OK)
     {
         System.Console.WriteLine("Calculation file md5 error,Err:" + errCode.ToString());
         if (_sw != null) _sw.WriteLine("(UTC:" + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + "): Calculation file md5 error,Err:" + errCode.ToString());
         try
         {
             File.Delete(filePath);
         }
         catch { }
         return false;
     }
     if (md5Code.ToLower() != currentMD5Code.ToLower())
     {
         System.Console.WriteLine("File md5 is not match!");
         if (_sw != null) _sw.WriteLine("(UTC:" + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + "): File md5 is not match!");
         try
         {
             File.Delete(filePath);
         }
         catch { }
         return false;
     }
     else return true;
 }