private void LoginWord() { LoginDto loginDto = new LoginDto(txtname.Text, txtpassword.Text); SQLUtilEvent sQLUtilEvent = new SQLUtilEvent(new LoginDto(txtname.Text, txtpassword.Text)); sQLUtilEvent.OnRunWorkerCompleted += new EventHandler <RunWorkerCompletedEventArgs>((object sender, RunWorkerCompletedEventArgs e) => { DataSet ds = (DataSet)e.Result; if (ds.Tables[0].Rows.Count == 1) { LocalConfig.SetConfigValue("name", txtname.Text); LocalConfig.SetConfigValue("pwd", EncryptUtil.Md532(txtpassword.Text)); LocalConfig.SetConfigValue("username", ds.Tables[0].Rows[0]["username"].ToString()); loginDto.Username = ds.Tables[0].Rows[0]["username"].ToString(); Plan plan = new Plan(loginDto); Hide(); plan.ShowDialog(); ProcessBarThread.Abort(); Application.ExitThread(); } else { btnlogin.Enabled = true; ProcessBarStop(); ShowMessageDialog("用户名密码错误"); } }); sQLUtilEvent.Run("login"); }
//添加标签选项卡 private void NewTagPage(string key, string text, Memo memo = null) { lblWelcome.Hide(); for (int i = 0; i < tabControlMain.TabPages.Count; i++) { if (tabControlMain.TabPages[i].Tag.Equals(key)) { tabControlMain.SelectTab(i); return; } } if (memo == null) { memo = MemoDal.Get(key); } TabPage page = new TabPage(); page.Text = text; page.Tag = key; RichTextBox txtBox = new RichTextBox(); txtBox.Parent = page; txtBox.Width = page.Width; txtBox.Height = page.Height; txtBox.Text = EncryptUtil.DecryptDes(memo.content); txtBox.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left; txtBox.KeyDown += new KeyEventHandler(RickTextBox_KeyDown); txtBox.TextChanged += new EventHandler(RTxtBoxTextChanged); tabControlMain.TabPages.Add(page); tabControlMain.SelectTab(page); }
//this is used to validate your user account with provided grant at /connect/token public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { try { //get your user model from db (by username - in my case its email) //var user = await _authorizationService.SingleAsync(c => c.Email == context.UserName || c.Mobile == context.UserName); var result = _authorizationService.VerifyPassword(context.UserName, EncryptUtil.EncryptMD5(context.Password)); //check if password match - remember to hash password if stored as hash in db if (result.Success && result.Data != null) { var userModel = result.Data; context.Result = new GrantValidationResult( subject: userModel.Id.ToString(), authenticationMethod: "custom", claims: Config.GetUserClaims(userModel, _rolesService)); } else { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "Invalid user or password"); } } catch (Exception ex) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest, ex.ToString()); } }
private void decryptBtn_Click(object sender, EventArgs e) { string encryption = encryptedPasswordTBox.Text.Trim(); string enSalt = passwordSaltKeyEnTBox.Text.Trim(); plainPasswordEnTBox.Text = EncryptUtil.Decrypt(encryption, enSalt); }
/// <summary> /// 用户登录 /// </summary> /// <param name="account"></param> /// <param name="password"></param> /// <returns></returns> public OperateResult <AuthorizationUser> Login(string account, string password) { var accountDetail = _sysAccountRepository.AccountDetail(a => a.UserName == account); OperateResult <AuthorizationUser> result = new OperateResult <AuthorizationUser>(); if (accountDetail == null) { result.Message = "用户名或密码错误"; return(result); } if (accountDetail.Password != EncryptUtil.MD5Encrypt32(accountDetail.AccountId + password)) { result.Message = "用户名或密码错误"; } else if (!accountDetail.EnabledMark) { result.Message = "登录账户已被禁用"; } else { result.Status = ResultStatus.Success; var user = accountDetail.MapTo <AuthorizationUser, AccountDetailsDto>(); user.LoginId = SnowflakeUtil.NextStringId(); user.HeadIcon = user.HeadIcon ?? "/images/default.png"; result.Data = user; } return(result); }
private bool DoEdit(int oid) { ht_manager manager = db.ht_manager.FirstOrDefault(x => x.id == oid); if (manager == null) { return(false); } manager.roleid = Convert.ToInt32(ddlRoleId.SelectedValue); var role = db.ht_manager_role.FirstOrDefault(x => x.id == Manager.roleid); if (role != null) { manager.roletype = role.roletype; } manager.islock = cbIsLock.Checked ? 0 : 1; //判断密码是否更改 if (txtPassword.Text.Trim() != defaultpassword) { //获取用户已生成的salt作为密钥加密 manager.password = EncryptUtil.DesEncrypt(txtPassword.Text.Trim(), manager.salt); } manager.nickname = txtRealName.Text; manager.mobile = txtTelephone.Text; db.SaveChanges(); AddAdminLog(HTEnums.ActionEnum.Edit.ToString(), "修改管理员:" + manager.username); return(true); }
public IActionResult Signup([FromBody] tblUser model) { try { model.Email = model.Email.Trim().ToLower(); model.Password = model.Password.Trim(); string password = model.Password; tblUser _tblUser = _ItblUserRepository.Get(x => x.Email.ToLower() == model.Email).FirstOrDefault(); if (_tblUser != null) { return(BadRequest("Email already exists")); } else { model.Password = EncryptUtil.EncryptString(model.Password); model.IsActive = true; model.CreatedDate = DateTime.Now; _ItblUserRepository.Add(model); model.Password = password; } return(Ok(model)); } catch (Exception ex) { log.Fatal("signup:", ex); return(BadRequest(ex)); } }
/// <summary> /// 登录验证 /// </summary> /// <param name="code">工号</param> /// <param name="password">密码</param> /// <returns>登录结果</returns> public LoginValidateModel Login(string code, string password) { var encryptPwd = EncryptUtil.Md5Hash(password); var user = _dbContext.Set <Employee>().Where(s => s.EmCode == code && (s.Password == encryptPwd || s.Password == password) && s.Disabled != true).FirstOrDefault(); if (user != null) { var userDto = Mapper.Map <Employee, EmployeeDto>(user); userDto.Password = ""; var token = EncryptUtil.AesEncrypt(string.Format("{0}|{1}", user.Id, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); return(new LoginValidateModel() { Valid = true, Token = token, User = userDto, Message = "Success", }); } else { return(new LoginValidateModel() { Valid = false, Token = "", User = null, Message = "账号或密码不正确", }); } }
/// <summary> /// Token验证 /// </summary> /// <param name="token"></param> /// <returns>true:验证通过,false:验证失败</returns> public bool ValidateToken(string token) { if (string.IsNullOrWhiteSpace(token)) { return(false); } var tokenObj = EncryptUtil.AesDecrypt(token); if (!string.IsNullOrEmpty(tokenObj)) { var strs = tokenObj.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); if (strs.Length == 2) { var createOn = strs[1]; DateTime createOnDate; if (DateTime.TryParse(createOn, out createOnDate)) { var expireMinutes = System.Configuration.ConfigurationManager.AppSettings["SessionExpireMinutes"] ?? "120"; if (createOnDate.AddMinutes(double.Parse(expireMinutes)) > DateTime.Now) { return(true); } } } } return(false); }
public string DoLoad(string luaScriptPath) { if (luaScriptPath.EndsWith(".lua")) { int index = luaScriptPath.LastIndexOf('.'); luaScriptPath = luaScriptPath.Substring(0, index); } byte[] buffer = LuaLoader(luaScriptPath); if (buffer == null || buffer.Length == 0) { return(null); } else { #if UNITY_EDITOR if (AssetManager.bundleLoadMode) { EncryptUtil.Decryption(buffer); } #else EncryptUtil.Decryption(buffer); #endif string txt = System.Text.Encoding.Default.GetString(buffer); return(txt); } }
/// <summary> /// 修改密码 /// </summary> /// <param name="userId">用户ID</param> /// <param name="srcPwd">原密码</param> /// <param name="newPwd">新密码</param> /// <returns></returns> public bool ChangePassword(string userId, string srcPwd, string newPwd) { if (string.IsNullOrEmpty(newPwd)) { throw new Exception("新密码不能为空!"); } var user = _dbContext.Set <Employee>().Where(s => s.Id == userId).FirstOrDefault(); if (user == null) { throw new Exception("用户不存在!"); } if (EncryptUtil.Md5Hash(srcPwd) == user.Password) { user.Password = EncryptUtil.Md5Hash(newPwd); _dbContext.SaveChanges(); return(true); } else { throw new Exception("原密码错误!"); } }
public void Init() { luaEnv.DoString(LuaManager.GetRequireString("LuaSetting"), "LuaSetting"); //沙盒是不传递到require的文件的,不适用lua使用self luaEnv.AddLoader((ref string filepath) => { GLog.Log("LuaLoader > " + filepath); byte[] buffer = LuaLoader(filepath); if (buffer == null || buffer.Length == 0) { return(null); } else { #if UNITY_EDITOR if (AssetManager.bundleLoadMode) { EncryptUtil.Decryption(buffer); } #else EncryptUtil.Decryption(buffer); #endif return(buffer); } }); GameEvent.SendEvent(GameEventType.LuaManagerReady); }
/// <summary> /// 验证密码是否正确 /// </summary> /// <param name="UserID">用户ID</param> /// <param name="Password">密码</param> /// <returns></returns> public bool CheckPassword(int UserID, string Password) { var dbModel = _db.Instance.Queryable <TUsersModel>().Where(p => p.Id == UserID).First(); var currPwd = EncryptUtil.DeAESbyKey(dbModel.LoginPwd, Encoding.UTF8, dbModel.Salt); return(string.Equals(Password, currPwd)); }
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { try { UserModel userModel = null; if (_authorizationService.VerifyPassword(context.UserName, EncryptUtil.EncryptMD5(context.Password), userModel: ref userModel)) { if (userModel != null) { context.Result = new GrantValidationResult( subject: userModel.Id.ToString(), authenticationMethod: "custom", claims: Config.GetUserClaims(userModel, _rolesService)); } else { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "User does not exist"); } } else { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "Incorrect password"); } } catch (Exception) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest, "Invalid request"); } }
private void 备份数据库_RarToolStripMenuItem_Click(object sender, EventArgs e) { SaveFileDialog fileDialog = new SaveFileDialog(); fileDialog.Filter = "备份文件 (*.rar)|*.rar|所有文件 (*.*)|*.*"; if (fileDialog.ShowDialog() == DialogResult.OK) { database.ResetConnection(); if (File.Exists(fileDialog.FileName)) { File.Delete(fileDialog.FileName); } if (WinRARUtil.CompressFile( new String[] { new FileInfo("TimeDatabase.mdf").FullName, new FileInfo("TimeDatabase_log.ldf").FullName }, fileDialog.FileName)) { if (EncryptUtil.EncryptFile_HC128(fileDialog.FileName)) { MessageBox.Show("无损备份数据库成功!", "备份成功", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { MessageBox.Show("备份失败!加密文件时发生未知错误。", "失败提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("备份失败!该操作需要电脑上装有WinRAR软件。", "失败提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public async Task <ReturnResult <bool> > ChangePassword(string id, string oldPassword, string newPassword) { return(await Aspect.Task(async() => { ReturnResult <bool> result = new ReturnResult <bool>(); Expression <Func <Users, bool> > exp = x => x.ID == id; var user = await this.FindOneAsync <UsersModel, Users>(repository, exp); oldPassword = EncryptUtil.EncryptDES(oldPassword, (user.registertime ?? DateTime.Now) .ToString(timeStyle)); if (user.password == oldPassword) { result.data = await this.Update <Users>(repository, id, x => x.password = EncryptUtil.EncryptDES(newPassword, (user.registertime ?? DateTime.Now).ToString(timeStyle))); if (result.data) { result.code = 1; } else { result.code = -103; result.message = "用户密码更新失败!"; } return result; } else { result.code = -102; result.message = "用户原密码错误!"; return result; } }) .WithLog("修改密码.") .Execute()); }
private bool DoAdd() { ht_manager manager = db.ht_manager.FirstOrDefault(x => x.username == txtUserName.Text); if (manager != null) { return(false); } var role = db.ht_manager_role.FirstOrDefault(x => x.id == Manager.roleid); if (role != null) { ht_manager model = new ht_manager { roleid = Convert.ToInt32(ddlRoleId.SelectedValue), islock = cbIsLock.Checked ? 0 : 1, username = txtUserName.Text, salt = Utils.GetCheckCode(10), roletype = role.roletype, mobile = txtTelephone.Text, nickname = txtRealName.Text, addtime = DateTime.Now }; model.password = EncryptUtil.DesEncrypt(txtPassword.Text.Trim(), model.salt); db.ht_manager.Add(model); db.SaveChanges(); } return(true); }
/// <summary> /// 收银员操作 /// </summary> /// <param name="request"></param> /// <returns></returns> public static CasherOpersResponse CasherOper(CasherOpersDto request) { request.sign = EncryptUtil.GetSign(request); var response = WebUtils.HttpPost <CasherOpersDto, CasherOpersResponse>("http://kls-gate.xuanlife.com.cn/casherOpers", request); return(response); }
/// <summary> /// 用户是否已经登录 /// </summary> /// <returns></returns> public bool ExistsLogin() { string base64Code = string.Empty; if (actionContext.Request.Headers.Contains("Authorization")) { base64Code = actionContext.Request.Headers.GetValues("Authorization").FirstOrDefault(); } if (base64Code.IsNull()) { return(false); } //code结构为:userid-UserAgent.MD5()-随机数-时间戳 string code = EncryptUtil.UnBase64(base64Code); string[] para = code.Split(new[] { "-" }, StringSplitOptions.RemoveEmptyEntries); if (para.Length != 4) { return(false); } string key = (para[0] + para[1] + para[3]).MD5(); if (!RedisBase.ContainsKey(key)) { return(false); } return(true); }
/// <summary> /// 下单 /// </summary> /// <param name="request"></param> public static TradePreCreateResponse Precreate(TradePreCreateDto request) { request.sign = EncryptUtil.GetSign(request); var response = WebUtils.HttpPost <TradePreCreateDto, TradePreCreateResponse>("http://118.178.35.56/tradeprecreate", request); return(response); }
public void GenPwdTest() { // string key = ""; //string randKey="" string plainText = "75730F7107706007C077700057D05"; //XOrTwoString(key, randKey); // original plaintext // LogUtil.HWLogger.DEFAULT.Info("plainText..." +Encoding.Unicode.GetBytes(plainText)+":" //+BitConverter.ToString(Encoding.Unicode.GetBytes(plainText)).Replace("-", String.Empty)); string saltValue = "668DAFB758034A97"; // can be any string string hashAlgorithm = "SHA256"; // can be "MD5" int passwordIterations = 10000; // can be any number int keySize = 128; // can be 192 or 128 /* * string trueEnKey = GenRootKey(plainText, saltValue, * hashAlgorithm, passwordIterations, keySize);*/ string trueEnKey = EncryptUtil.GenRootKey(plainText, saltValue, passwordIterations, keySize); byte[] keyBytes = new byte[32]; byte[] saltValueBytes = strToToHexByte(saltValue); EncryptUtil.PKCS5_PBKDF2_HMAC(plainText, 16, saltValueBytes, 16, passwordIterations, EncryptUtil.EVP_sha256(), 32, keyBytes); trueEnKey = BitConverter.ToString(keyBytes).Replace("-", String.Empty); LogUtil.HWLogger.DEFAULT.Info("trueEnKey..." + trueEnKey); Console.WriteLine(trueEnKey); }
/// <summary> /// 查询 /// </summary> /// <param name="request"></param> public static QueryResponse Query(QueryDto request) { request.sign = EncryptUtil.GetSign(request); var response = WebUtils.HttpPost <QueryDto, QueryResponse>("http://118.178.35.56/query", request); return(response); }
/// <summary> /// 将请求接口中的业务明文参数加密并请求一键支付接口,单不对返回的数据进行解密,用于获取清算对账单接口--商户通用接口 /// </summary> /// <param name="sd"></param> /// <param name="apiUri"></param> /// <returns></returns> private string createMerchantDataAndRequestYb2(SortedDictionary <string, object> sd, string apiUri, bool ispost) { //随机生成商户AESkey string merchantAesKey = AES.GenerateAESKey(); //生成RSA签名 string sign = EncryptUtil.handleRSA(sd, merchantPrivatekey); sd.Add("sign", sign); //将对象转换为json字符串 string bpinfo_json = Newtonsoft.Json.JsonConvert.SerializeObject(sd); string datastring = AES.Encrypt(bpinfo_json, merchantAesKey); //将商户merchantAesKey用RSA算法加密 string encryptkey = RSAFromPkcs8.encryptData(merchantAesKey, yibaoPublickey, "UTF-8"); String ybResult = ""; if (ispost) { ybResult = YJPayUtil.payAPIRequest(apimercahntprefix + apiUri, datastring, encryptkey, true); } else { ybResult = YJPayUtil.payAPIRequest(apimercahntprefix + apiUri, datastring, encryptkey, false); } return(YJPayUtil.checkYbClearResult(ybResult)); }
/// <summary> /// 退款 /// </summary> /// <param name="request"></param> public static RefundResponse Refund(RefundDto request) { request.sign = EncryptUtil.GetSign(request); var response = WebUtils.HttpPost <RefundDto, RefundResponse>("http://118.178.35.56/refund", request); return(response); }
//[MenuItem("Tools/Decrypt Lua Code", false, 101)] static void DecryptLuaCode() { try { string[] files = Directory.GetFiles(Application.dataPath + "/Build/LuaScripts", "*.lua", SearchOption.AllDirectories); for (int i = 0; i < files.Length; i++) { string name = files[i]; name = name.Replace('\\', '/'); name = name.Replace(Application.dataPath + "/Build/", ""); string outName = @"C:\Users\Administrator\Desktop\" + name; GameUtil.CreateDirectory(outName); //byte[] decryptBytes = EncryptUtil.DecryptFileToBytes(files[i], "19930822"); //byte[] decompressedBytes = GameUtil.DecompressBytes(decryptBytes); //File.WriteAllBytes(outName, decompressedBytes); EncryptUtil.DecryptFile(files[i], outName, "19930822"); //GameUtil.CreateDirectory(outName); //File.WriteAllBytes(outName, EncryptUtil.DecryptBytes(File.ReadAllBytes(files[i]), "19930822")); EditorUtility.DisplayProgressBar("decrypt lua code...", name, (float)i / files.Length); } EditorUtility.ClearProgressBar(); AssetDatabase.Refresh(); } catch (Exception ex) { EditorUtility.ClearProgressBar(); AssetDatabase.Refresh(); throw new Exception(ex.Message + "\n" + ex.StackTrace); } }
public static CancelResponse Cancel(CancelDto request) { request.sign = EncryptUtil.GetSign(request); var response = WebUtils.HttpPost <CancelDto, CancelResponse>("http://118.178.35.56/reverse", request); return(response); }
private Dictionary <string, string> GetParams(string method, Dictionary <string, string> q, Type objType) { Dictionary <string, string> req_params = new Dictionary <string, string>(); foreach (string key in q.Keys) { if (!string.IsNullOrEmpty(q[key])) { req_params.Add(key, q[key]); } } if (objType != null) { //返回字段列表 req_params.Add("fields", helper.GetDataObjFieldsString(objType)); } //系统级输入参数 //api_key req_params.Add("api_key", currentAppKey); //返回格式 req_params.Add("format", "xml"); //api方法名 req_params.Add("method", method); //时间戳 req_params.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")); //版本 req_params.Add("v", currentVersion); //应用级输入参数 //sign,生成签名字符串 string sign = EncryptUtil.Signature(req_params, currentAppSecret, "sign"); req_params.Add("sign", sign); return(req_params); }
private void 导入所有数据ToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog fileDialog = new OpenFileDialog(); fileDialog.Filter = "还原文件 (*.rar)|*.rar|所有文件 (*.*)|*.*"; if (fileDialog.ShowDialog() == DialogResult.OK) { database.ResetConnection(); String file = fileDialog.FileName; String rawRarTempFilename = file.Insert(file.Length - 4, "_rawfile"); if (EncryptUtil.DecryptFile_HC128(file, rawRarTempFilename)) { if (WinRARUtil.DecompressFile(rawRarTempFilename, Directory.GetCurrentDirectory())) { MessageBox.Show("无损还原数据库成功!", "还原成功", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { MessageBox.Show("还原失败!该操作需要电脑上装有WinRAR软件。", "失败提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("还原失败!解密文件时发生未知错误。", "失败提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } File.Delete(rawRarTempFilename); Application.Restart(); } }
public IHttpActionResult Authenticate([FromBody] UserLogin login) { IHttpActionResult response; HttpResponseMessage httpResponse = null; if (login != null) { login = new BLLogin().Login(login.UserName, EncryptUtil.MD5Hash(login.Password)); } if (login != null) { // Tài khoản mật khẩu hợp lệ thì Tạo Token string token = CreateToken(login.UserName); // return Ok<string>(token); httpResponse = Request.CreateResponse(HttpStatusCode.OK, new ServiceResult(true, null, token, null)); } else { // Nếu không hợp lệ thì trả về lỗi httpResponse = Request.CreateResponse(HttpStatusCode.Unauthorized, new ServiceResult(false, ErrorCode.InvalidPassword)); } response = ResponseMessage(httpResponse); return(response); }
/// <summary> /// 登录 /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public override async Task <LoginResult> Login(LoginForm input, ServerCallContext context) { var hash = Configuration["Customization:PwdKey"]; var user = await _mediator.Send(new LoginInput() { IpAddress = input.IpAddress, Password = EncryptUtil.AESEncrypt(input.Password, hash), PhoneNumber = input.PhoneNumber }, context.CancellationToken); var expired = DateTime.Now.AddMinutes(120); var claims = new Claim[] { new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Sid, user.UserId.ToString()), new Claim("Ip", input.IpAddress), new Claim("TenantId", user.TenantId.ToString()), //租户 new Claim(ClaimTypes.MobilePhone, user.PhoneNumber) }; return(new LoginResult() { Token = JsonConvert.SerializeObject(_tokenBuilder.BuildJwtToken(claims, DateTime.UtcNow, expired)) }); }