public void PostBufferTest() { string url = "http://api.admin.52stark.cn/api/Store/SingleOrDefault/1161"; double ts = new TimeStamp(); string timestamp = ((long)ts).ToString(); var data = new { merchantNo = "1019", timestamp = timestamp, token = "6Hcb2V9xoTWvSvn1WXCFt5VcDiMJybD3rqg3SS6PaVeu", apiversion = "v1", }; string source = string.Concat("path=/api/Store/SingleOrDefault/1161×tamp=", data.timestamp, "&token=", data.token, "&key=", "1ad9b656c59c44329e40f58d5750c6bb"); string sign = MD5.Encode(source); //string json = JsonSerializer.JsonSerialize(data); //byte[] buffer = Encoding.UTF8.GetBytes(json); HttpHelper http = new HttpHelper(url); http.AddHeaderData("merchantNo", data.merchantNo) .AddHeaderData("timestamp", data.timestamp) .AddHeaderData("token", data.token) .AddHeaderData("signature", sign) .AddHeaderData("apiversion", "v1"); string response = http.SendRequest("get", null, 10, false); var httpRes = http.GetResponse(); Assert.IsTrue(http.StatusCode == 200); }
public string ChangeAdminPwd(HttpContext context) { int userID = 0; string pwd = context.Request.Form["pwd"]; if (!string.IsNullOrEmpty(pwd) && int.TryParse(context.Request.Form["pid"], out userID) && userID > 0) { BCtrl_SysUser bll = new BCtrl_SysUser(); pwd = MD5.Encode(WebKeys.AdminPwdRandom, pwd.Trim()); bool isSuccess = bll.UpdatePassword(userID, pwd); if (isSuccess) { ClearCacheOrSession.ClearAdminCacheByCRUD(userID); return("{\"status\":1}"); } else { return("{\"status\":0}"); } } else { return("{\"status\":-1}"); } }
/// <summary> /// 检查签名 /// </summary> /// <param name="xml"></param> /// <param name="key"></param> /// <returns></returns> public static bool CheckSign(string xml, string key) { XElement root = XElement.Parse(xml); var eles = root.Elements(); string sign = null; AsciiSortedDictionary <string> keyValues = new AsciiSortedDictionary <string>(); foreach (var item in eles) { if (!"sign".Equals(item.Name.LocalName, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(item.Value)) { keyValues.Add(item.Name.LocalName, item.Value); } else if ("sign".Equals(item.Name.LocalName, StringComparison.OrdinalIgnoreCase)) { sign = item.Value; } } StringBuilder builder = new StringBuilder(); keyValues.Aggregate(builder, (b, kv) => b.Append(kv.Key).Append("=").Append(kv.Value).Append("&")); builder.Append("key=").Append(key); Debug.WriteLine(builder.ToString()); string mSign = MD5.Encode(builder.ToString()); return(mSign.Equals(sign, StringComparison.OrdinalIgnoreCase)); }
public void EncodeTest() { const string data = "i am testing"; MD5 md5 = new MD5(); var result = md5.Encode(data); Assert.IsTrue(result == "C6BD2686D765C25433A11810493987BD"); }
public JsonResult CambiarClave(CambiarClaveModeloVista entidad) { var claveEncriptar = AppSettings.Get <string>(ConstantesWebConfig.CLAVE_ENCRYPTACION); string json = string.Empty; try { json = TripleDES.Decode(Base64.DecodeUrl(entidad.param), MD5.Encode(claveEncriptar)); } catch (System.Security.Cryptography.CryptographicException e) { throw new NegocioExcepcion("El link no tiene un formato adecuado."); } dynamic obj = JsonConvert.DeserializeObject <dynamic>(json); int usuarioId = obj.Id; string clave = obj.Clave; var usuario = _repository.Get(usuarioId); if (usuario.Clave.Equals(clave)) { usuario.Clave = TripleDES.Encode(entidad.clave, MD5.Encode(claveEncriptar)); _repository.SaveOrUpdate(usuario); } else { throw new NegocioExcepcion("Este link ya se utilizó para cambiar su clave."); } return(Json(true, JsonRequestBehavior.AllowGet)); }
public User ToUser() { String pass = null; if (this.NewPassword != null) { pass = MD5.Encode(this.NewPassword); } else { pass = this.Password; } User user = new User { Id = this.Id, Name = this.Name, Surname = this.Surname, Email = this.Email, Password = pass, Role = this.Role }; return(user); }
public JsonResult Create(UsuarioModeloVista usuarioViewModel) { Usuario usuario = new Usuario(); usuario.Apellidos = usuarioViewModel.Apellidos; usuario.Correo = usuarioViewModel.Correo; var claveEncriptar = AppSettings.Get <string>(ConstantesWebConfig.CLAVE_ENCRYPTACION); var claveEncriptada = TripleDES.Encode(usuarioViewModel.Clave, MD5.Encode(claveEncriptar)); usuario.Clave = claveEncriptada; usuario.Cuenta = usuarioViewModel.Cuenta; usuario.Estado = usuarioViewModel.Estado; usuario.PersonaId = usuarioViewModel.PersonaId; usuario.Nombres = usuarioViewModel.Nombres; var rolesSistema = _iUsuarioService.GetRolesSistema(); var rolesSeleccionados = rolesSistema.Where(rs => usuarioViewModel.RolIds.Contains(rs.Id)); foreach (var rolSeleccionado in rolesSeleccionados) { usuario.Roles.Add(rolSeleccionado); } usuario = _iUsuarioService.Guardar(usuario); var usuarioVista = new { usuario.Id, usuario.Apellidos, usuario.Correo, usuario.Cuenta, usuario.Estado, usuario.PersonaId, usuario.Nombres }; return(Json(usuarioVista, JsonRequestBehavior.AllowGet)); }
public void Encode() { Assert.Equal("81DC9BDB52D04DC20036DBD8313ED055", MD5.Encode("1234")); Assert.Equal(new byte[] { 0x81, 0xDC, 0x9B, 0xDB, 0x52, 0xD0, 0x4D, 0xC2, 0x00, 0x36, 0xDB, 0xD8, 0x31, 0x3E, 0xD0, 0x55 }, MD5.Encode(Encoding.UTF8.GetBytes("1234"))); Assert.Equal("65A8E27D8879283831B664BD8B7F0AD4", MD5.Encode("Hello, World!")); Assert.Equal(new byte[] { 0x65, 0xA8, 0xE2, 0x7D, 0x88, 0x79, 0x28, 0x38, 0x31, 0xB6, 0x64, 0xBD, 0x8B, 0x7F, 0x0A, 0xD4 }, MD5.Encode(Encoding.UTF8.GetBytes("Hello, World!"))); }
public override bool ValidateUser(string username, string password) { var claveEncriptar = AppSettings.Get <string>(ConstantesWebConfig.CLAVE_ENCRYPTACION); var claveEncriptada = TripleDES.Encode(password, MD5.Encode(claveEncriptar)); //throw new NegocioExcepcion("ClaveEncriptar: "+claveEncriptar + " y ClaveEncriptada: "+ claveEncriptada); var user = repository.Get(username); return(user.Clave.Equals(claveEncriptada)); }
/// <summary> /// Generates a file name for a VS solution file which will contain the given set of projects. /// </summary> /// <param name="projects">Set of projects to be included in the SLN file</param> /// <returns>Returns a valid file name without extension</returns> public string GetName(IEnumerable <Project> projects) { var result = MD5.Encode(string.Join(",", from project in projects let module = project.Module let fullName = module + "." + project.Name select fullName)); return(result); }
/// <summary> /// Generates a file name for a VS solution file which will contain the given set of projects. /// </summary> /// <param name="projects">Set of projects to be included in the SLN file</param> /// <returns>Returns a valid file name without extension</returns> public string GetName(IEnumerable <Project> projects) { var result = MD5.Encode(string.Join(",", from project in projects let module = project.Module let fullName = module + "." + project.Name select fullName)); log.DebugFormat("Using hash based sln name: {0}", result); return(result); }
public ActionResult Create(User user) { if (ModelState.IsValid) { user.Password = MD5.Encode(user.Password); userdao.Create(user); return(RedirectToAction("Index", "Users")); } else { ViewBag.RoleItems = items.Roles(); return(View(user)); } }
/// <summary> /// 登录操作 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnLogin_Click(object sender, EventArgs e) { try { BaseVariable.NetworkStatus = NetStatus; BaseVariable.ServerStatus = ServerStatus; string UserID = this.txtUser.Text.Trim().ToString(); string UserPwd = this.txtPwd.Text.Trim().ToString(); UserInfoMDL UserInfo = null; if (!NetStatus || !ServerStatus) { UserInfo = lUserDAL.GetModel(UserID); } else { UserInfo = UserDAL.GetModel(UserID); } if (UserInfo != null) { string UserPwdMD5 = MD5.Encode(UserPwd, 32).ToUpper(); if (UserInfo.UserPwd.ToUpper() == UserPwdMD5) { BaseVariable.UserEntity = UserInfo; XmlHelper xml = new XmlHelper(); xml.UpdateInnerText("/Root/User/UserID", UserID); xml.UpdateInnerText("/Root/User/UserPwd", UserPwd); FrmMain form = new FrmMain(); form.Owner = this; form.Show(); this.Hide(); } else { MessageBox.Show("密码错误"); } } else { MessageBox.Show("用户不存在"); } } catch (Exception ex) { this.lblMsg.Text = "服务器连接失败"; CLog.WriteErrLog(ex.Message); } }
public ActionResult LogOn(string cuenta, string clave) { var usuario = _repository.Get(cuenta); var claveEncriptar = AppSettings.Get <string>(ConstantesWebConfig.CLAVE_ENCRYPTACION); var claveEncriptada = TripleDES.Encode(clave, MD5.Encode(claveEncriptar)); if (usuario != null && usuario.Clave.Equals(claveEncriptada) && usuario.Roles.Any(r => r.EsAdministrador)) { FormsAuthentication.SetAuthCookie(cuenta, false); return(Redirect("~/elmah.axd")); } else { ModelState.AddModelError("", "Usted no esta autorizado para realizar esta acción."); } return(View()); }
public ActionResult Index(LoginModel model) { if (ModelState.IsValid) { User user = userdao.GetByEmail(model.Email); if (user != null && MD5.Encode(model.Password) == user.Password) { FormsAuthentication.SetAuthCookie(model.Email, false); return(RedirectToAction("index", "home")); } { ModelState.AddModelError("", "Invalid email or password"); } } return(View()); }
public ActionResult SignUp(User user) { if (ModelState.IsValid) { if (userdao.GetByEmail(user.Email) != null) { ViewData["ErrorMessage"] = "Email already exist."; return(View(user)); } user.Password = MD5.Encode(user.Password); userdao.Create(user); TempData["SuccessMessage"] = "User was successfully signed up."; return(RedirectToAction("index", "login")); } else { return(View(user)); } }
protected override object[] HttpCallAuth(HttpClient _http, string _method, ref string _url, object[] _keyValues) { Dictionary <string, string> _list = new Dictionary <string, string>(); if (_method.ToUpper() == "POST") { for (int i = 0; i < _keyValues.Length; i += 2) { _list.Add(_keyValues[i].ToString(), _keyValues[i + 1].ToString()); } } string _time = DateTimePlus.DateTime2JSTime(DateTime.UtcNow.AddSeconds(-1)).ToString(); _list.Add("api_key", base.Key); _list.Add("auth_nonce", _time); KeyValuePair <string, string>[] _sorted = _list.OrderBy(c => c.Key).ToArray(); string _sign = ""; foreach (KeyValuePair <string, string> _item in _sorted) { _sign += _item.Value; } _list.Add("auth_sign", MD5.Encode(_sign + base.Secret).ToLower()); IList <string> _keyValueList = new List <string>(); if (_method.ToUpper() == "GET") { foreach (var _item in _keyValues) { _keyValueList.Add(_item.ToString()); } } foreach (KeyValuePair <string, string> _item in _list) { _keyValueList.Add(_item.Key); _keyValueList.Add(_item.Value); } return(_keyValueList.ToArray()); }
protected override object[] HttpCallAuth(HttpClient _http, string _method, ref string _url, object[] _keyValues) { IList <object> _result = new List <object>(); SortedDictionary <string, string> _list = new SortedDictionary <string, string>(); for (int i = 0; i < _keyValues.Length; i += 2) { _list.Add(_keyValues[i].ToString(), _keyValues[i + 1].ToString()); _result.Add(_keyValues[i]); _result.Add(_keyValues[i + 1]); } string _sign = ""; long _time = DateTimePlus.DateTime2JSTime(DateTime.UtcNow.AddSeconds(-1)) * 1000; _list.Add("access_id", base.Key); _list.Add("tonce", _time.ToString()); _result.Add("access_id"); _result.Add(base.Key); _result.Add("tonce"); _result.Add(_time.ToString()); foreach (KeyValuePair <string, string> _item in _list) { _sign += _sign == "" ? "" : "&"; _sign += $"{_item.Key}={_item.Value}"; } _sign += $"&secret_key={base.Secret}"; _sign = MD5.Encode(_sign).ToUpper(); _http.Headers.Add("authorization", _sign); return(_result.ToArray()); }
/// <summary> /// 提交表单 /// </summary> private void SubmitForm() { if (ValidateData()) { BCtrl_SysUser bllSysuser = new BCtrl_SysUser(); bool isSuccess = false; AdminEntity entity = null; if (pid > 0) { #region 修改 entity = bllSysuser.QuerySysUserEntity(pid); if (entity != null) { entity.TrueName = this.txtTruename.Value.Trim(); entity.User_Sex = int.Parse(this.selsex.Value); entity.User_Tel = this.txtUser_Tel.Value.Trim(); entity.User_Mobile = this.txtUser_Mobile.Value.Trim(); entity.User_Mail = this.txtUser_Mail.Value.Trim(); entity.User_DeptID = int.Parse(this.selDepartMent.Value); isSuccess = bllSysuser.Update(entity); if (isSuccess) { Page.ClientScript.RegisterStartupScript(this.GetType(), "adminEdit", "<script>bootbox.dialog(\"保存成功!\", [{\"label\": \"OK\",\"class\": \"btn-small btn-primary\",callback: function () {window.location.href = 'AdminManager.aspx?fun=" + Master.fun + "';}}]);</script>"); } else { Page.ClientScript.RegisterStartupScript(this.GetType(), "adminEdit", "<script>bootbox.alert(\"保存失败\");</script>"); } } else { Page.ClientScript.RegisterStartupScript(this.GetType(), "adminEdit", "<script>bootbox.dialog(\"当前用户不存在或已被删除!\", [{\"label\": \"OK\",\"class\": \"btn-small btn-primary\",callback: function () { window.location.href = 'AdminManager.aspx?fun=" + Master.fun + "';}}]);</script>"); } #endregion } else { #region 新增 entity = new AdminEntity(); entity.User_Name = this.txtLoginname.Value.Trim(); entity.TrueName = this.txtTruename.Value.Trim(); entity.User_Pwd = MD5.Encode(WebKeys.AdminPwdRandom, this.txtUserpwd.Value.Trim()); entity.User_Sex = int.Parse(this.selsex.Value); entity.User_Tel = this.txtUser_Tel.Value.Trim(); entity.User_Mobile = this.txtUser_Mobile.Value.Trim(); entity.User_Mail = this.txtUser_Mail.Value.Trim(); entity.User_DeptID = int.Parse(this.selDepartMent.Value); entity.IsValid = false; entity.RegisterDate = DateTime.Now; isSuccess = bllSysuser.Insert(entity); if (isSuccess) { Page.ClientScript.RegisterStartupScript(this.GetType(), "adminEdit", "<script>bootbox.dialog(\"添加成功!\", [{\"label\": \"OK\",\"class\": \"btn-small btn-primary\",callback: function () {window.location.href = 'AdminManager.aspx?fun=" + Master.fun + "';}}]);</script>"); } else { Page.ClientScript.RegisterStartupScript(this.GetType(), "adminEdit", "<script>bootbox.alert(\"添加失败\");</script>"); } #endregion } } else { Page.ClientScript.RegisterStartupScript(this.GetType(), "adminEdit", "<script>bootbox.alert(\"请检查必填项或数据格式是否正确\");</script>"); } }
public JsonResult RecuperarCredencial(RecuperarCredencialModeloVista cuenta) { string plantilla = string.Empty; switch (cuenta.accion) { case 0: plantilla = ConstantesPlantillas.RUTA_PLANTILLA_RECUPERACION_CLAVE; break; case 1: plantilla = ConstantesPlantillas.RUTA_PLANTILLA_RECUPERACION_CUENTA; break; default: throw new Exception("No existe una implementacion para una accion: " + cuenta.accion); } var rutaPlantillaRecuperacion = Path.Combine(AppContext.BaseDirectory, plantilla); var html = System.IO.File.ReadAllText(rutaPlantillaRecuperacion); var claveEncriptar = AppSettings.Get <string>(ConstantesWebConfig.CLAVE_ENCRYPTACION); var persona = _repositoryPersona.GetQuery(p => p.Correo != null && p.Correo.Equals(cuenta.correo)).FirstOrDefault(); if (persona == null) { throw new NegocioExcepcion("No existe una persona para el correo proporcionado."); } var usuario = _repository.GetByPersona(persona.Id); if (usuario == null) { throw new NegocioExcepcion("No existe una cuenta para el correo proporcionado."); } var sitioUrl = AppSettings.Get <string>(ConstantesWebConfig.SITIO_URL); switch (cuenta.accion) { case 0: var token = TripleDES.Encode(JsonConvert.SerializeObject(new { Id = usuario.Id, Clave = usuario.Clave }), MD5.Encode(claveEncriptar)); html = string.Format(html, persona.ToString(), sitioUrl, Base64.EncodeUrl(token)); Mail.enviar(new List <string> { persona.Correo }, html, "Recuperación de clave"); break; case 1: html = string.Format(html, persona.ToString(), usuario.Cuenta); Mail.enviar(new List <string> { persona.Correo }, html, "Recuperación de Cuenta"); break; default: throw new Exception("No existe una implementacion para una accion: " + cuenta.accion); } return(Json(true, JsonRequestBehavior.AllowGet)); }
public string AdminLogins(HttpContext context) { string loginname = context.Request.Form["un"]; string password = context.Request.Form["pw"]; string valid = context.Request.Form["va"]; string returnUrl = context.Request.Form["url"]; if (string.IsNullOrEmpty(loginname) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(valid)) { return("{\"state\":-9}"); //传递参数不完整 } else { if (valid.Equals(DateTime.Now.Day.ToString())) { BCtrl_SysUser sysUserBll = new BCtrl_SysUser(); #region 管理员登录验证 string userid = ""; password = MD5.Encode(WebKeys.AdminPwdRandom, password); //尝试登录 //if (new PassportServiceProxy().TryLogin(loginname, password, "NewBookSystem", out userid)) if (sysUserBll.TryLogin(loginname, password, out userid)) { if (!string.IsNullOrEmpty(userid)) { //查询用户所属角色能访问的频道 List <FunctionEntity> list = new BCtrl_Function().GetFunction(userid); if (list.Count != 0) { AdminSessionEntity ue = new BCtrl_SysUser().QuerySysUserInfo(userid); if (ue != null) { ue.Sys_LoginName = loginname; ue.Sys_UserID = userid; ue.Functions = list; context.Session[WebKeys.AdminSessionKey] = ue; return("{\"state\":1}"); //登录成功 } else { return("{\"state\":-7}"); //登录成功但在系统中为找到授权 } } else { return("{\"state\":-6}"); //登录成功但无使用功能权限 } } else { return("{\"state\":-1}"); //登录失败 用户名密码错误 } } else { return("{\"state\":-1}"); //登录失败 用户名密码错误 } #endregion #region 搭建时测试 //if (loginname == "zl" && password == "123456") //{ // AdminSessionEntity ue = new AdminSessionEntity(); // ue.Sys_LoginName = loginname; // ue.Sys_UserID = "1"; // context.Session[WebKeys.AdminSessionKey] = ue; // string result = "{\"state\":1, \"url\":\"" + returnUrl + "\"}"; // return result; //登录成功 //} //else //{ // return "{\"state\":-1}"; //登录失败 用户名密码错误 //} #endregion } else { //验证码不正确 return("{\"state\":-8}"); //验证码不正确 } } }
public string SignData(string original) { return(MD5.Encode(original + SecretKey)); }
public bool VerifySignature(string original, string sign) { string mSign = MD5.Encode(original + "&key=" + SecretKey); return(mSign.Equals(sign, StringComparison.OrdinalIgnoreCase)); }