public JsonResult Validate(string userId, string password) { var user = _userMasterService.GetCachedModel(userId); if (user == null) { return(Json(new ResultInfo() { ErrorNo = -1, ErrorMsg = ResMessage.AccountNotExist })); } if (user.Password != DesEncrypt.Encrypt(password)) { return(Json(new ResultInfo() { ErrorNo = -1, ErrorMsg = ResMessage.AccountNotExist })); } return(Json(new ResultInfo() { ErrorNo = 0, ErrorMsg = "" })); }
public async Task <DataAPIResult <UserInfoDTO> > Add(UserInfo user) { var result = new DataAPIResult <UserInfoDTO> { data = new UserInfoDTO() }; if (user == null) { result.Fail("数据不能为空"); return(result); } try { user.CreateTime = DateTime.Now; user.GUID = Guid.NewGuid().ToString(); user.PassWord = DesEncrypt.Encrypt(user.PassWord); //user.PassWord = MD5Encrypt.Encrypt(user.PassWord); await db.UserInfo.AddAsync(user); await db.SaveChangesAsync(); var userInfo = await db.UserInfo.Where(a => a.GUID == user.GUID).FirstAsync(); result.data = mapper.Map <UserInfoDTO>(userInfo); result.Success(); } catch (Exception ex) { log.LogError(ex.Message); result.Fail(ex.Message); } return(result); }
/// <summary> /// 用户登录验证 /// </summary> /// <param name="model">用户视图实体类</param> /// <param name="inputPassword">用户输入的密码</param> /// <returns></returns> public static ValidateResponseModel LoginValidator(this LocalUserViewModel model, string inputPassword, string clientId) { var response = ValidateResponseModelFactory.Instance; response.IsValid = true; if (model == null) { response.Message = "登录名不存在"; return(response); } if (model.State == 0) { response.Message = "用户已被锁定"; } //TODO:处理密码 if (DesEncrypt.Encrypt(inputPassword) != model.Password) { response.Message = "密码不正确"; } //if (model.ClientId != clientId) //{ // response.Message = "无效的客户端应用ID"; //} if (response.Message.Length > 0) { response.IsValid = false; } return(response); }
public IHttpActionResult Create(AppViewModel model) { var entity = model.ToModel(); entity.a_time = DateTime.Now; entity.a_state = 1; entity.a_rid = 0; entity.a_key = ""; entity.a_secretkey = ""; var a = _iAppService.Insert(entity); DataSourceForm dataSourceForm = new DataSourceForm(); if (a > 0) { entity.a_key = DesEncrypt.Encrypt(entity.a_user_id + ";" + a + ";" + DateTime.Now.ToString("yyyyMMddssmmfff")); entity.a_secretkey = DesEncrypt.Encrypt(a + ";" + entity.a_key + ";" + DateTime.Now.ToString("yyyyMMddssmmfff")); entity.a_id = a; if (_iAppService.Update(entity)) { dataSourceForm.IsSuccess = true; dataSourceForm.Message = "添加成功!"; _logFactory.Logger.CreateLog("新增应用", entity); } } else { dataSourceForm.IsSuccess = false; dataSourceForm.Message = "添加失败!"; } return(Ok(dataSourceForm)); }
public void SubmitForm(AppUser userEntity, string roleIds) { if (userEntity.Id == 0) { userEntity.Create(); string userPassword = "******";//默认密码 userEntity.UserSecretkey = Md5Helper.Md5(Utils.CreateNo(), 16).ToLower(); userEntity.LoginPassword = Md5Helper.Md5(DesEncrypt.Encrypt(Md5Helper.Md5(userPassword, 32).ToLower(), userEntity.UserSecretkey).ToLower(), 32).ToLower(); userEntity.LoginCount = 0; //新增时配置角色 if (roleIds.IsNotNullOrEmpty()) { foreach (string id in roleIds.Split(',')) { int.TryParse(id, out int result); if (result == 0) { continue; } AppUserRole userRoleEntity = new AppUserRole { RoleId = result }; userEntity.UserRoles.Add(userRoleEntity); } } this.Insert(userEntity); } else { using (var db = new RepositoryBase().BeginTrans()) { userEntity.Modify(userEntity.Id); string[] modifystrs = { "LoginName", "StatusCode", "Email", "NickName", "LastModifyUserId", "LastModifyTime" }; this.Update(userEntity, modifystrs); db.Delete <AppUserRole>(u => u.UserId == userEntity.Id); if (roleIds.IsNotNullOrEmpty()) { foreach (string id in roleIds.Split(',')) { int.TryParse(id, out int result); if (result == 0) { continue; } AppUserRole userRoleEntity = new AppUserRole { RoleId = result, UserId = (int)userEntity.Id }; db.Insert(userRoleEntity); } } db.Commit(); } } }
public ActionResult CheckLogin(string username, string password, string code) { LogBaseEntity logBaseEntity = new LogBaseEntity(); logBaseEntity.F_ModuleName = "系统登录"; logBaseEntity.F_Type = DbLogType.Login.ToString(); try { if (Session["nfine_session_verifycode"].IsEmpty() || Md5.md5(code.ToLower(), 16) != Session["nfine_session_verifycode"].ToString()) { throw new Exception("验证码错误,请重新输入"); } var userBaseEntity = new UserService().CheckLogin(username, password); if (userBaseEntity != null) { OperatorModel operatorModel = new OperatorModel(); operatorModel.UserId = userBaseEntity.F_Id; operatorModel.UserCode = userBaseEntity.F_Account; operatorModel.UserName = userBaseEntity.F_RealName; operatorModel.CompanyId = userBaseEntity.F_OrganizeId; operatorModel.DepartmentId = userBaseEntity.F_DepartmentId; operatorModel.RoleId = userBaseEntity.F_RoleId; operatorModel.LoginIPAddress = Net.Ip; operatorModel.LoginIPAddressName = Net.GetLocation(operatorModel.LoginIPAddress); operatorModel.LoginTime = DateTime.Now; operatorModel.LoginToken = DesEncrypt.Encrypt(Guid.NewGuid().ToString()); if (userBaseEntity.F_Account == "admin") { operatorModel.IsSystem = true; } else { operatorModel.IsSystem = false; } OperatorProvider.Provider.AddCurrent(operatorModel); logBaseEntity.F_Account = userBaseEntity.F_Account; logBaseEntity.F_NickName = userBaseEntity.F_RealName; logBaseEntity.F_Result = true; logBaseEntity.F_Description = "登录成功"; new LogService().WriteDbLog(logBaseEntity); } return(Content(new AjaxResult { state = ResultType.success.ToString(), message = "登录成功。" }.ToJson())); } catch (Exception ex) { logBaseEntity.F_Account = username; logBaseEntity.F_NickName = username; logBaseEntity.F_Result = false; logBaseEntity.F_Description = "登录失败," + ex.Message; new LogService().WriteDbLog(logBaseEntity); return(Content(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }.ToJson())); } }
public void ResetPassword(AppUser userEntity, string userPassword) { userEntity.UserSecretkey = Md5Helper.Md5(Utils.CreateNo(), 16).ToLower(); userEntity.LoginPassword = Md5Helper.Md5(DesEncrypt.Encrypt(Md5Helper.Md5(userPassword, 32).ToLower(), userEntity.UserSecretkey).ToLower(), 32).ToLower(); string[] modifstr = { "UserSecretkey", "LoginPassword", }; this.Update(userEntity, modifstr); }
public static string Encrypt(string pwd) { if (string.IsNullOrWhiteSpace(pwd)) { return(string.Empty); } return(Md5.md5(DesEncrypt.Encrypt(Md5.md5(pwd, 32), Settings.UserSecretkey).ToLower(), 32).ToLower()); }
public (string token, byte[] image) GenerateCode() { var code = Utils.RndEnNum(4); var image = securityCodeHelper.GetEnDigitalCodeByte(code); var token = jwtEncoder.Encode(new Payload { Code = DesEncrypt.Encrypt(code, secret), ExpiredAt = (long)UnixEpoch.GetSecondsSince(timeProvider.GetNow().AddMinutes(10)) }, secretBytes); return(token, image); }
public void AddCurrent(OnlineUser operatorModel) { if (LoginProvider == "Cookie") { WebHelper.WriteCookie(OnlineUserKey, DesEncrypt.Encrypt(operatorModel.ToJson()), 60); } else { WebHelper.WriteSession(OnlineUserKey, DesEncrypt.Encrypt(operatorModel.ToJson())); } }
public void RevisePassword(string userPassword, string keyValue) { UserLogOnBaseEntity userLogOnBaseEntity = new UserLogOnBaseEntity { F_Id = keyValue, F_UserSecretkey = Md5.md5(Common.Common.CreateNo(), 16).ToLower() }; userLogOnBaseEntity.F_UserPassword = Md5.md5(DesEncrypt.Encrypt(Md5.md5(userPassword, 32).ToLower(), userLogOnBaseEntity.F_UserSecretkey).ToLower(), 32).ToLower(); service.Update(userLogOnBaseEntity); }
/// <summary> /// 添加用户 /// </summary> /// <param name="user"></param> /// <returns></returns> public UserContract AddUser(UserContract user) { user.UserId = Guid.NewGuid(); var entity = user.MapTo <UserEntity>(); entity.CreateTime = DateTime.Now; entity.Secretkey = SecurityHelper.GetSha256Hash(WatchHelper.CreateNo(), 16).ToLower(); entity.Password = SecurityHelper.GetSha256Hash(DesEncrypt.Encrypt(SecurityHelper.GetSha256Hash(user.Password, 32).ToLower(), entity.Secretkey).ToLower(), 32).ToLower(); this._db.User.Add(entity); this._db.SaveChanges(); return(user); }
public void AddCurrent(OperatorModel operatorModel) { if (LoginProvider == "Cookie") { WebHelper.WriteCookie(LoginUserKey, DesEncrypt.Encrypt(operatorModel.ToJson()), 60); } else { WebHelper.WriteSession(LoginUserKey, DesEncrypt.Encrypt(operatorModel.ToJson())); } WebHelper.WriteCookie("nfine_mac", Md5.md5(Net.Net.GetMacByNetworkInterface().ToJson(), 32)); //WebHelper.WriteCookie("nfine_licence", Licence.GetLicence()); }
public OnlineUser Login(UserLoginDto dto) { //if (!SecurityCodeService.IsValid(dto.Token, dto.SecurityCode)) // throw new Exception("错误:图形验证码错误!"); if (string.IsNullOrEmpty(dto.AccountName)) { throw new Exception("账号为空!"); } if (string.IsNullOrEmpty(dto.Password)) { throw new Exception("密码为空!"); } try { var user = CheckLogin(dto.AccountName, dto.Password); if (user != null) { OnlineUser onlineUser = new OnlineUser { UserId = user.Id, AccountName = user.AccountName, UserName = user.RealName, NickName = user.NickName, LoginIPAddress = Net.Ip }; onlineUser.LoginIPAddressName = Net.GetLocation(onlineUser.LoginIPAddress); onlineUser.LoginTime = DateTime.Now; onlineUser.LoginToken = DesEncrypt.Encrypt(Guid.NewGuid().ToString()); if (user.AccountName == "admin") { onlineUser.IsSystem = true; } else { onlineUser.IsSystem = false; } OnlineUserProvider.Provider.AddCurrent(onlineUser); return(onlineUser); } throw new Exception("用户不存在!"); } catch (Exception ex) { throw ex; } }
/// <summary> /// 检查用户 /// </summary> /// <param name="account"></param> /// <param name="password"></param> /// <returns></returns> public UserContract CheckUser(string account, string password) { var user = this._db.User.FirstOrDefault(e => e.UserAccount == account); if (user != null) { string encryPassword = SecurityHelper.GetSha256Hash(DesEncrypt.Encrypt(SecurityHelper.GetSha256Hash(password, 32).ToLower(), user.Secretkey).ToLower(), 32).ToLower(); if (encryPassword == user.Password) { return(user.MapTo <UserContract>()); } } return(null); }
public ActionResult Index(FormCollection fc) { if (!string.IsNullOrEmpty(Request["name"]) && !string.IsNullOrEmpty(Request["pwd"])) { var name = Request["name"]; var pwd = Request["pwd"]; var user = _userBll.Query(name); if (user == null) { SetTempData("用户不存在,请核对账号是否正确!"); return(RedirectToAction("Index")); } if (user.IsLock) { SetTempData("用户已锁定,请联系管理员进行解锁!"); return(RedirectToAction("Index")); } if (DesEncrypt.Encrypt(pwd, user.Salt) != user.Password) { SetTempData("密码错误,请重新输入!"); return(RedirectToAction("Index")); } var roleIdList = user?.Roles.Select(x => x.RoleId).Distinct(); //登陆重定向 Session.Add("User", user); Session.Add("RoleIdList", roleIdList); var userIdentity = new UserIdentity(user.LoginName, true, 7200); foreach (var role in user.Roles) { userIdentity.Roles.Add(role.Code); } //认证 var token = AuthManager.Login(userIdentity); CacheHelper.Insert(user.LoginName, token, 7200); return(RedirectToAction("Index", "Manager")); } else { SetTempData("用户名或者密码不能为空!"); return(RedirectToAction("Index")); } }
public ActionResult ResetPwd(string newPwd, string loginPassword = "") { int userId = (int)Op.CurrentUser.UserId; if (newPwd.IsNullOrEmpty()) { return(Error("新密码不能为空")); } AppUser userEntity = _appUserRepository.FindEntity(userId); if (userEntity != null) { //当旧密码为空时,直接重置 if (userEntity.LoginPassword.IsNullOrEmpty()) { _appUserRepository.ResetPassword(userEntity, newPwd); return(Success("您的密码已经设置成功,请牢记你的密码噢!")); } else { if (loginPassword.IsNullOrEmpty()) { return(Error("旧密码不能为空")); } if (userEntity.UserSecretkey.IsNullOrEmpty()) { return(Error("用户密钥丢失,请联系管理员重置密码")); } string dbPwd = Md5Helper.Md5(DesEncrypt.Encrypt(loginPassword.ToLower(), userEntity.UserSecretkey).ToLower(), 32).ToLower(); if (userEntity.LoginPassword.Equals(dbPwd)) { _appUserRepository.ResetPassword(userEntity, newPwd); return(Success("您的密码已经设置成功,请牢记你的密码噢!")); } else { return(Error("你的旧密码填写不对,无法重置密码!")); } } } else { return(Error("当前用户不存在")); } }
/// <summary> /// 更新密码 /// </summary> /// <param name="entityAccountPwd"></param> public async Task UpdateAccountPwd(EntityAccountPwd entityAccountPwd) { var userSalt = Utils.GetCheckCode(16); var model = new TableAccountManager() { Id = entityAccountPwd.Id, UserPwd = DesEncrypt.Encrypt(entityAccountPwd.UserPwd.Trim().Trim(), userSalt), UserSalt = userSalt }; var accountRep = GetRepositoryInstance <TableAccountManager>(); accountRep.Update <TableAccountManager>(model, managerInfo => new { managerInfo.UserPwd, managerInfo.UserSalt }); }
static void Main(string[] args) { try { #region MD5 //1 防止看到明文 数据库密码,加盐(原密码+固定字符串,然后再MD5/双MD5) //2 防篡改 //急速秒传(第一次上传文件,保存md5摘要,第二次上传检查md5摘要) //文件下载(防篡改,官方发布的时候给一个md5摘要,安装的时候首先检查下摘要) //svn TFS git VSS(本地保存文件的md5摘要,任何修改都会影响md5) //3 防止抵赖 Console.WriteLine(MD5Encrypt.Encrypt("1")); Console.WriteLine(MD5Encrypt.Encrypt("1")); Console.WriteLine(MD5Encrypt.Encrypt("123456小李")); Console.WriteLine(MD5Encrypt.Encrypt("113456小李")); Console.WriteLine(MD5Encrypt.Encrypt("113456小李113456小李113456小李113456小李113456小李113456小李113456小李")); string md5Abstract1 = MD5Encrypt.AbstractFile(@"D:\ruanmou\online9\homework\1\Advanced9第一次作业优秀合集.rar"); string md5Abstract2 = MD5Encrypt.AbstractFile(@"D:\ruanmou\online9\homework\1\Advanced9第一次作业优秀合集 - 副本.rar"); #endregion #region Des //可逆对称加密 string desEn = DesEncrypt.Encrypt("王殃殃"); string desDe = DesEncrypt.Decrypt(desEn); string desEn1 = DesEncrypt.Encrypt("张三李四"); string desDe1 = DesEncrypt.Decrypt(desEn1); #endregion #region Rsa //可逆非对称加密 KeyValuePair <string, string> encryptDecrypt = RsaEncrypt.GetKeyPair(); string rsaEn1 = RsaEncrypt.Encrypt("net", encryptDecrypt.Key); //key是加密的 string rsaDe1 = RsaEncrypt.Decrypt(rsaEn1, encryptDecrypt.Value); //value 解密的 不能反过来用的 //加密钥 解密钥 钥匙的功能划分 //公钥 私钥 公开程度划分 #endregion } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.Read(); }
/// <summary> /// AddUserBase /// </summary> /// <param name="entity"></param> /// <returns></returns> public UserBase AddUserBase(UserBase entity) { using (var db = DbContext.CreateInstance()) { #region 重构数据 var salt = Encrypt.GetCheckCode(5); entity.Salt = salt; entity.Password = DesEncrypt.Encrypt(entity.Password, entity.Salt); entity.Id = Guid.NewGuid().ToString(); entity.CreateTime = DateTime.Now; #endregion db.Insert(entity); return(entity); } }
/// <summary> /// 创建COOKIE对象并赋Value值 /// </summary> /// <param name="CookiesName">COOKIE对象名</param> /// <param name="IExpires">COOKIE对象有效时间(秒数),1表示永久有效,0和负数都表示不设有效时间,大于等于2表示具体有效秒数,31536000秒=1年=(60*60*24*365),</param> /// <param name="CookiesValue">COOKIE对象Value值</param> public static void WriteCookies(string CookiesName, int IExpires, string CookiesValue) { HttpCookie objCookie = new HttpCookie(CookiesName.Trim()); objCookie.Value = DesEncrypt.Encrypt(CookiesValue.Trim()); //加密存储 if (IExpires > 0) { if (IExpires == 1) { objCookie.Expires = DateTime.MaxValue; } else { objCookie.Expires = DateTime.Now.AddMinutes(IExpires); } } HttpContext.Current.Response.Cookies.Add(objCookie); }
public IActionResult Init() { using var trans = organizeService.DbContext.Database.BeginTransaction(); var organizeCat = new OrganizeCategoryEntity { Name = "管理办公室", Category = OrganizeCategoryEntity.Categories.Main, }; organizeCatService.Update(organizeCat); var organize = new OrganizeEntity { Name = "研发运维", CategoryId = organizeCat.Id, Category = organizeCat, }; organizeService.Update(organize); var user = new UserEntity { UserName = "******", RealName = "运维超级账号", Contract = "{\"wechat\":\"loyieking\"}", IsAdministrator = true, Password = Md5.Hash(DesEncrypt.Encrypt("adminadmin").ToLower(), 32).ToLower() }; userService.Update(user); var userOrganize = new UserOrganizeEntity { User = user, Organize = organize }; userOrganizeService.Update(userOrganize); trans.Commit(); return(Success()); }
public void SubmitForm(UserBaseEntity userBaseEntity, UserLogOnBaseEntity userLogOnBaseEntity, string keyValue) { using (var db = new RepositoryBase().BeginTrans()) { if (!string.IsNullOrEmpty(keyValue)) { db.Update(userBaseEntity); } else { userLogOnBaseEntity.F_Id = userBaseEntity.F_Id; userLogOnBaseEntity.F_UserId = userBaseEntity.F_Id; userLogOnBaseEntity.F_UserSecretkey = Md5.md5(Nice.Common.Common.CreateNo(), 16).ToLower(); userLogOnBaseEntity.F_UserPassword = Md5.md5(DesEncrypt.Encrypt(Md5.md5(userLogOnBaseEntity.F_UserPassword, 32).ToLower(), userLogOnBaseEntity.F_UserSecretkey).ToLower(), 32).ToLower(); db.Insert(userBaseEntity); db.Insert(userLogOnBaseEntity); } db.Commit(); } }
/// <summary> /// Post请求 /// </summary> /// <param name="userDto"></param> /// <param name="saveState"></param> /// <param name="array"></param> public void HttpPostSave(UserDto userDto, SaveState saveState, int[] array) { switch (saveState.OperationState) { case OperationState.Add: var salt = Encrypt.GetCheckCode(5); userDto.Salt = salt; userDto.Password = DesEncrypt.Encrypt(userDto.Password, salt); //盐值加密 _userService.Add(userDto, array); break; case OperationState.Update: userDto.Password = DesEncrypt.Encrypt(userDto.Password, userDto.Salt); //盐值加密 _userService.Update(userDto, array); break; default: break; } }
public void Excute() { if (!_dbContext.AppRole.Any()) { _dbContext.AppRole.Add(new AppRole() { RoleName = "超级管理员", IsEnableMark = true, DeleteMark = false }); } if (!_dbContext.AppUser.Any()) { string userSecretkey = Md5Helper.Md5(Utils.CreateNo(), 16).ToLower(); string loginPassword = Md5Helper.Md5(DesEncrypt.Encrypt(Md5Helper.Md5("123qwe", 32).ToLower(), userSecretkey).ToLower(), 32).ToLower(); _dbContext.AppUser.AddOrUpdate(new AppUser() { LoginName = "admin", LoginPassword = loginPassword, UserSecretkey = userSecretkey, DeleteMark = false }); } _dbContext.SaveChanges(); if (!_dbContext.UserRole.Any()) { List <AppUser> users = _dbContext.AppUser.ToList(); users?.ForEach(r => { _dbContext.UserRole.Add(new AppUserRole() { UserId = r.Id, RoleId = 1 }); }); } }
/// <summary> /// 创建COOKIE对象并赋多个KEY键值 /// 设键/值如下: /// NameValueCollection myCol = new NameValueCollection(); /// myCol.Add("red", "rojo"); /// myCol.Add("green", "verde"); /// myCol.Add("blue", "azul"); /// myCol.Add("red", "rouge"); 结果“red:rojo,rouge;green:verde;blue:azul” /// </summary> /// <param name="CookiesName">COOKIE对象名</param> /// <param name="IExpires">COOKIE对象有效时间(秒数),1表示永久有效,0和负数都表示不设有效时间,大于等于2表示具体有效秒数,31536000秒=1年=(60*60*24*365),</param> /// <param name="CookiesKeyValueCollection">键/值对集合</param> public static void WriteCookies(string CookiesName, int IExpires, NameValueCollection CookiesKeyValueCollection) { HttpCookie objCookie = new HttpCookie(CookiesName.Trim()); foreach (String key in CookiesKeyValueCollection.AllKeys) { objCookie[key] = DesEncrypt.Encrypt(CookiesKeyValueCollection[key].Trim()); } if (IExpires > 0) { if (IExpires == 1) { objCookie.Expires = DateTime.MaxValue; } else { objCookie.Expires = DateTime.Now.AddSeconds(IExpires); } } HttpContext.Current.Response.Cookies.Add(objCookie); }
public UserBaseEntity CheckLogin(string username, string password) { UserBaseEntity userBaseEntity = service.FindEntity(t => t.F_Account == username); if (userBaseEntity != null) { if (userBaseEntity.F_EnabledMark == true) { UserLogOnBaseEntity userLogOnBaseEntity = _userLogOnService.GetForm(userBaseEntity.F_Id); string dbPassword = Md5.md5(DesEncrypt.Encrypt(password.ToLower(), userLogOnBaseEntity.F_UserSecretkey).ToLower(), 32).ToLower(); if (dbPassword == userLogOnBaseEntity.F_UserPassword) { DateTime lastVisitTime = DateTime.Now; int LogOnCount = (userLogOnBaseEntity.F_LogOnCount).ToInt() + 1; if (userLogOnBaseEntity.F_LastVisitTime != null) { userLogOnBaseEntity.F_PreviousVisitTime = userLogOnBaseEntity.F_LastVisitTime.ToDate(); } userLogOnBaseEntity.F_LastVisitTime = lastVisitTime; userLogOnBaseEntity.F_LogOnCount = LogOnCount; _userLogOnService.UpdateForm(userLogOnBaseEntity); return(userBaseEntity); } else { throw new Exception("密码不正确,请重新输入"); } } else { throw new Exception("账户被系统锁定,请联系管理员"); } } else { throw new Exception("账户不存在,请重新输入"); } }
public ViewResult ResetPassword(string oldPassword, string newPassword, string confirmPassword) { var user = _userMasterService.GetModel(SessionManager.GetUserMaster().UserID); if (newPassword == oldPassword) { return(View(new ResultInfo() { ErrorNo = -1, ErrorMsg = ResUserMaster.NewPasswordCannotEquelOldPassword })); } if (newPassword != confirmPassword) { return(View(new ResultInfo() { ErrorNo = -1, ErrorMsg = "两次新密码不一致" })); } if (user.Password != DesEncrypt.Encrypt(oldPassword)) { return(View(new ResultInfo() { ErrorNo = 0, ErrorMsg = ResMessage.PasswordError })); } user.Password = DesEncrypt.Encrypt(newPassword); _userMasterService.Update(user); return(View(new ResultInfo() { ErrorNo = 0, ErrorMsg = ResSuggest.UpdateSuccess })); }
static void Main(string[] args) { {//MD5 //非对称不可逆 Console.WriteLine("*************************************非对称不可逆 MD5****************************************"); string fileNmae = @"F:\志翔学校.rar"; string fileNmaeCopy = @"F:\志翔学校 - 副本.rar"; Console.WriteLine(MD5Encrypt.Encrypt("123")); Console.WriteLine(MD5Encrypt.Encrypt("123")); Console.WriteLine(MD5Encrypt.Encrypt("321null")); Console.WriteLine("文件MD5 Soure:" + MD5Encrypt.AbstractFile(fileNmae)); Console.WriteLine("文件MD5 Copy:" + MD5Encrypt.AbstractFile(fileNmaeCopy)); } {//DesEncrypt //对称可逆加密 //速度比较快 Console.WriteLine("*************************************对称可逆加密 DES****************************************"); string des = DesEncrypt.Encrypt("1233211234567890"); string res = DesEncrypt.Decrypt(des); Console.WriteLine("Desc:" + des); Console.WriteLine("ESC:" + res); } {//Ras //非对称可逆加密 //速度比较慢 Console.WriteLine("*************************************非对称可逆加密 RSA****************************************"); KeyValuePair <string, string> encryptDecrypt = RsaEncrypt.GetKeyPair(); string rsaEn1 = RsaEncrypt.Encrypt("222222", encryptDecrypt.Key); string rsaDe1 = RsaEncrypt.Decrypt(rsaEn1, encryptDecrypt.Value); Console.WriteLine("加密:" + rsaEn1); Console.WriteLine("解密:" + rsaDe1); Console.WriteLine("公钥:" + encryptDecrypt.Key); Console.WriteLine("私钥:" + encryptDecrypt.Value); } {//Ras test //非对称可逆加密 //速度比较慢 Console.WriteLine("*************************************非对称可逆加密 RSA****************************************"); RSAUtil rsa = new RSAUtil(); //rsa.CreateRSAKey(); //StreamReader reader1 = new StreamReader("privatekey.xml"); //XmlDocument document1 = new XmlDocument(); //document1.LoadXml(reader1.ReadToEnd()); //XmlElement element1 = (XmlElement)document1.SelectSingleNode("root"); //parameters1.Modulus = ReadChild(element1, "Modulus"); //var r1 = rsa.ToHexString(rsa.ReadChild(element1, "Exponent")); //var r2 = rsa.ToHexString(rsa.ReadChild(element1, "D")); //var r3 = rsa.ToHexString(rsa.ReadChild(element1, "Q")); //var r4 = rsa.ToHexString(rsa.ReadChild(element1, "P")); var en = rsa.EnCrypt("123"); var doEn = rsa.DoEncrypt(en); Console.WriteLine("原文:" + doEn); Console.WriteLine("密文:" + en); Console.WriteLine("解密:" + doEn); //Console.WriteLine(r1); //Console.WriteLine(r2); //Console.WriteLine(r3); //Console.WriteLine(r4); //parameters1.DP = ReadChild(element1, "DP"); //parameters1.DQ = ReadChild(element1, "DQ"); //parameters1.P = ReadChild(element1, "P"); //parameters1.Q = ReadChild(element1, "Q"); //parameters1.InverseQ = ReadChild(element1, "InverseQ"); //reader1.Close(); } Console.ReadKey(); }
/// <summary> /// 扩展方法:DES加密 /// </summary> /// <param name="str">加密字符串</param> /// <param name="key">加密key</param> /// <returns>加密结果</returns> public static string Encrypt(this string str, string key = "TEMPKEY") { return(DesEncrypt.Encrypt(str, key)); }