public async Task <IActionResult> Login([FromBody] SysAdminLogin parm) { var apiRes = new ApiResult <string>() { statusCode = (int)ApiEnum.HttpRequestError }; var token = ""; try { ////获得公钥私钥,解密 var rsaKey = MemoryCacheService.Default.GetCache <List <string> >("LOGINKEY_" + parm.number); if (rsaKey == null) { apiRes.message = "登录失败,请刷新浏览器再次登录"; return(Ok(apiRes)); } var ras = new RSACrypt(rsaKey[0], rsaKey[1]); parm.password = ras.Decrypt(parm.password); } catch (Exception ex) { apiRes.message = ex.Message; apiRes.statusCode = (int)ApiEnum.Error; } apiRes.statusCode = (int)ApiEnum.Status; apiRes.data = token; return(Ok(apiRes)); }
/// <summary> /// 登录 /// </summary> /// <param name="parm">登录信息参数</param> /// <param name="privateKey">加密私钥</param> /// <param name="publicKey">加密公钥</param> /// <returns></returns> public async Task <IActionResult> OnPostLoginAsync(SysAdminLogin parm, string privateKey, string publicKey) { var apiRes = new ApiResult <Core.Model.Sys.SysAdmin>(); var token = ""; try { //Ras解密密码 var ras = new RSACrypt(privateKey, publicKey); parm.password = ras.Decrypt(parm.password); //查询登录结果 apiRes = _sysAdminService.LoginAsync(parm).Result; var user = apiRes.data; if (apiRes.statusCode == 200) { var identity = new ClaimsPrincipal( new ClaimsIdentity(new[] { new Claim(ClaimTypes.Sid, user.Guid), new Claim(ClaimTypes.Role, user.DepartmentName), new Claim(ClaimTypes.Thumbprint, user.HeadPic), new Claim(ClaimTypes.Name, user.TrueName), new Claim(ClaimTypes.WindowsAccountName, user.LoginName), new Claim(ClaimTypes.UserData, user.UpLoginDate.ToString()), }, CookieAuthenticationDefaults.AuthenticationScheme) ); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddHours(2), IsPersistent = true, AllowRefresh = false }); var tm = new TokenModel() { Uid = Guid.NewGuid().ToString(), Role = "Admin", Project = "Manage", TokenType = "Web" }; token = JwtHelper.IssueJWT(tm); } } catch (Exception ex) { apiRes.message = ex.Message; apiRes.statusCode = (int)ApiEnum.Error; } return(new JsonResult(new ApiResult <string>() { statusCode = apiRes.statusCode, message = apiRes.message, data = token })); }
public void RSATests_String_EncryptDecrypt(string text) { using (var cryptor = new RSACrypt()) { var cryptBuffer = Encoding.UTF8.GetBytes(text); var encryptBuffer = cryptor.Encrypt(cryptBuffer); var decryptBuffer = cryptor.Decrypt(encryptBuffer); var resultString = Encoding.UTF8.GetString(decryptBuffer); Assert.AreEqual(resultString, text); } }
private void button1_Click(object sender, EventArgs e)//sender { string appSign = "UrfaDiyarbakir"; if (listBox1.SelectedIndex >= 0) { char[] charsToTrim = { ' ', '"' }; int index = listBox1.SelectedIndex; var dateTime = DateTime.Now; string mailfrom = logformobj.getUsrName(); string mailpass = logformobj.getUsrPass(); try { string encryptedAESkey = friends[index, 0].Trim(charsToTrim); string decryptedAESkey = RSAobj.Decrypt(encryptedAESkey); string mailTo = friends[index, 2].Trim(charsToTrim); var post = new MailMessage(mailfrom, mailTo); string MailSign = textBox1.Text + "\n" + dateTime; string cryptedMailSign = RSAobj.SignData(MailSign); post.Subject = AesCrypt.EncryptParam(textBox2.Text, decryptedAESkey); post.Body = AesCrypt.Encrypt(appSign) + "---AppSign---" + AesCrypt.Encrypt(EncryptedMailApp.LoginForm.user) + "---Username---" + AesCrypt.EncryptParam(textBox1.Text + "\n" + dateTime, decryptedAESkey) + "---Body---" + cryptedMailSign + "---Sign---"; ; using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587)) { smtp.Credentials = new NetworkCredential(mailfrom, mailpass); smtp.EnableSsl = true; if (!string.IsNullOrEmpty(textBox3.Text)) { EncryptedMailApp.CryptoStuff.EncryptFile(password, textBox3.Text, textBox3.Text + "crp"); Attachment data = new Attachment(textBox3.Text + "crp"); post.Attachments.Add(data); smtp.Send(post); MessageBox.Show("Email Sent With Attachment"); } else { smtp.Send(post); MessageBox.Show("Email Sent"); } } } catch { MessageBox.Show("ERROR"); } } else { MessageBox.Show("There is no selected friend!"); } }
public void RSATests_BigString_EncryptDecrypt(string fileName) { using (var cryptor = new RSACrypt()) { var text = File.ReadAllText(fileName); var cryptBuffer = Encoding.UTF8.GetBytes(text); var encryptBuffer = cryptor.Encrypt(cryptBuffer); var decryptBuffer = cryptor.Decrypt(encryptBuffer); var resultString = Encoding.UTF8.GetString(decryptBuffer); Assert.AreEqual(resultString, text); } }
public async Task <ApiResult <LoginOutput> > SignIn([FromBody] LoginInput loginInput) { var rsaKey = _cache.Get <List <string> >("LOGINKEY" + loginInput.NumberGuid); if (rsaKey == null) { return(new ApiResult <LoginOutput>("登录失败,请刷新浏览器再次登录!")); } //Ras解密密码 var ras = new RSACrypt(rsaKey[0], rsaKey[1]); loginInput.Password = ras.Decrypt(loginInput.Password); var result = await _userService.LoginAsync(loginInput); var token = GetJwtToken(result.Data); if (string.IsNullOrEmpty(token)) { return(new ApiResult <LoginOutput>("生成的token字符串为空!")); } result.Data.Token = token; return(result); }
public async Task <IActionResult> Login([FromBody] SysAdminLogin parm) { var apiRes = new ApiResult <string>() { statusCode = (int)ApiEnum.HttpRequestError }; var token = ""; try { //获得公钥私钥,解密 var rsaKey = MemoryCacheService.Default.GetCache <List <string> >("LOGINKEY"); if (rsaKey == null) { apiRes.message = "登录失败,请刷新浏览器再次登录"; return(Ok(apiRes)); } //Ras解密密码 var ras = new RSACrypt(rsaKey[0], rsaKey[1]); parm.password = ras.Decrypt(parm.password); //获得用户登录限制次数 var configLoginCount = Convert.ToInt32(ConfigExtensions.Configuration[KeyHelper.LOGINCOUNT]); //获得登录次数和过期时间 var loginConfig = MemoryCacheService.Default.GetCache <SysAdminLoginConfig>(KeyHelper.LOGINCOUNT) ?? new SysAdminLoginConfig(); if (loginConfig.Count != 0 && loginConfig.DelayMinute != null) { //说明存在过期时间,需要判断 if (DateTime.Now <= loginConfig.DelayMinute) { apiRes.message = "您的登录以超过设定次数,请稍后再次登录~"; return(Ok(apiRes)); } else { //已经过了登录的预设时间,重置登录配置参数 loginConfig.Count = 0; loginConfig.DelayMinute = null; } } //查询登录结果 var dbres = await _adminService.LoginAsync(parm); if (dbres.statusCode != 200) { //增加登录次数 loginConfig.Count += 1; //登录的次数大于配置的次数,则提示过期时间 if (loginConfig.Count == configLoginCount) { var configDelayMinute = Convert.ToInt32(ConfigExtensions.Configuration[KeyHelper.LOGINDELAYMINUTE]); //记录过期时间 loginConfig.DelayMinute = DateTime.Now.AddMinutes(configDelayMinute); apiRes.message = "登录次数超过" + configLoginCount + "次,请" + configDelayMinute + "分钟后再次登录"; return(Ok(apiRes)); } //记录登录次数,保存到session MemoryCacheService.Default.SetCache(KeyHelper.LOGINCOUNT, loginConfig); //提示用户错误和登录次数信息 apiRes.message = dbres.message + " 您还剩余" + (configLoginCount - loginConfig.Count) + "登录次数"; return(Ok(apiRes)); } var user = dbres.data.admin; var identity = new ClaimsPrincipal( new ClaimsIdentity(new[] { new Claim(ClaimTypes.Sid, user.Guid), new Claim(ClaimTypes.Role, user.DepartmentName), new Claim(ClaimTypes.Thumbprint, user.HeadPic), new Claim(ClaimTypes.Name, user.LoginName), new Claim(ClaimTypes.WindowsAccountName, user.LoginName), new Claim(ClaimTypes.UserData, user.UpLoginDate.ToString()) }, CookieAuthenticationDefaults.AuthenticationScheme) ); //如果保存用户类型是Session,则默认设置cookie退出浏览器 清空 if (ConfigExtensions.Configuration[KeyHelper.LOGINSAVEUSER] == "Session") { await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties { AllowRefresh = false }); } else { //根据配置保存浏览器用户信息,小时单位 var hours = int.Parse(ConfigExtensions.Configuration[KeyHelper.LOGINCOOKIEEXPIRES]); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddHours(hours), IsPersistent = true, AllowRefresh = false }); } //获得第一条站点,并保存到session中 var site = await _siteService.GetListAsync(m => !m.IsDel, m => m.AddTime, DbOrderEnum.Asc); //把权限存到缓存里 var menuSaveType = ConfigExtensions.Configuration[KeyHelper.LOGINAUTHORIZE]; if (menuSaveType == "Redis") { RedisHelper.Set(KeyHelper.ADMINMENU + "_" + dbres.data.admin.Guid, dbres.data.menu); RedisHelper.Set(KeyHelper.NOWSITE, site.data.FirstOrDefault()); } else { MemoryCacheService.Default.SetCache(KeyHelper.NOWSITE, site.data.FirstOrDefault()); MemoryCacheService.Default.SetCache(KeyHelper.ADMINMENU + "_" + dbres.data.admin.Guid, dbres.data.menu, 600); } token = JwtHelper.IssueJWT(new TokenModel() { Uid = user.Guid, UserName = user.LoginName, Role = "Admin", TokenType = "Web" }); MemoryCacheService.Default.RemoveCache("LOGINKEY"); MemoryCacheService.Default.RemoveCache(KeyHelper.LOGINCOUNT); #region 保存日志 var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { Guid = Guid.NewGuid().ToString(), Logged = DateTime.Now, Logger = LogEnum.LOGIN.GetEnumText(), Level = "Info", Message = "登录:" + parm.loginname, Callsite = "/fytadmin/login", IP = Utils.GetIp(), User = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); #endregion } catch (Exception ex) { apiRes.message = ex.Message; apiRes.statusCode = (int)ApiEnum.Error; #region 保存日志 var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { Guid = Guid.NewGuid().ToString(), Logged = DateTime.Now, Logger = LogEnum.LOGIN.GetEnumText(), Level = "Error", Message = "登录失败!" + ex.Message, Exception = ex.Message, Callsite = "/fytadmin/login", IP = Utils.GetIp(), User = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); #endregion } apiRes.statusCode = (int)ApiEnum.Status; apiRes.data = token; return(Ok(apiRes)); }
public async Task <IActionResult> OnPostSubmitAsync(LoginInput loginInput) { var apiResult = new ApiResult <LoginOutput>() { StatusCode = 500, Success = false }; try { if (string.IsNullOrEmpty(loginInput.Captcha)) { apiResult.Msg = "ÑéÖ¤Âë´íÎó!"; return(new JsonResult(apiResult)); } var vcode = HttpContext.Session.GetString("vcode"); if (string.IsNullOrEmpty(vcode)) { apiResult.Msg = "·þÎñ¶ËÑéÖ¤Âë´íÎó!"; return(new JsonResult(apiResult)); } if (!vcode.ToLower().Equals(loginInput.Captcha.ToLower())) { apiResult.Msg = "ÑéÖ¤Âë´íÎó!"; return(new JsonResult(apiResult)); } var rsaKey = _cache.Get <List <string> >(LoginKey + loginInput.NumberGuid); if (rsaKey == null) { apiResult.Msg = "µÇ¼ʧ°Ü£¬ÇëË¢ÐÂä¯ÀÀÆ÷ÔٴεǼ!"; return(new JsonResult(apiResult)); } if (string.IsNullOrEmpty(loginInput.LoginName) || string.IsNullOrEmpty(loginInput.Password)) { apiResult.Msg = "Óû§ºÍÃÜÂë±ØÌî!"; return(new JsonResult(apiResult)); } //Ras½âÃÜÃÜÂë var ras = new RSACrypt(rsaKey[0], rsaKey[1]); loginInput.Password = ras.Decrypt(loginInput.Password); var result = await _httpHelper.PostAsync <ApiResult <LoginOutput> >("user/page-sign-in", JsonConvert.SerializeObject(loginInput), "application/json"); if (result.StatusCode == 500) { return(new JsonResult(result)); } //´æȨÏÞ _cache.Set($"frontAuthMenu:{result.Data.Id}", result.Data.MenuAuthOutputs); var identity = new ClaimsPrincipal( new ClaimsIdentity(new[] { new Claim(ClaimTypes.Sid, result.Data.Id.ToString()), new Claim(ClaimTypes.Name, result.Data.LoginName), new Claim(ClaimTypes.WindowsAccountName, result.Data.LoginName), new Claim(ClaimTypes.UserData, result.Data.LoginTime), new Claim("mobile", result.Data.Mobile), new Claim("trueName", result.Data.TrueName) }, CookieAuthenticationDefaults.AuthenticationScheme) ); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddHours(1), IsPersistent = true, AllowRefresh = false }); _cache.Remove(LoginKey + loginInput.NumberGuid); return(new JsonResult(result)); } catch (Exception e) { apiResult.Msg = e.Message; return(new JsonResult(apiResult)); } }
private void GetMail() { string mailfrom = logform.getUsrName(); string mailpass = logform.getUsrPass(); try { Task.Run(() => { using (ImapClient client = new ImapClient("imap.gmail.com", 993, mailfrom, mailpass, AuthMethod.Login, true)) { if (client.Supports("IDLE") == false) { MessageBox.Show("Server do not support IMAP IDLE"); return; } string cryptedAppSign = AesCrypt.Encrypt("UrfaDiyarbakir"); var uids = client.Search(SearchCondition.Text(cryptedAppSign)); int index = 0; foreach (var id in uids) { var m = client.GetMessage(id, FetchOptions.Normal); int a = m.Body.IndexOf("---AppSign---") + "---AppSign---".Length; int b = m.Body.IndexOf("---Username---"); int c = m.Body.IndexOf("---Username---") + "---Username---".Length; int d = m.Body.IndexOf("---Body---"); int e = m.Body.IndexOf("---Body---") + "---Body---".Length; int f = m.Body.IndexOf("---Sign---"); string appsign = m.Body.Substring(0, m.Body.IndexOf("---AppSign---")); string Username = AesCrypt.Decrypt(m.Body.Substring(a, b - a)); string sign = m.Body.Substring(e, f - e); string encryptedBody = m.Body.Substring(c, d - c); string dir = EncryptedMailApp.LoginForm.user; char[] charsToTrim = { ' ', '"' }; string encryptedAES = FbClient.Get(EncryptedMailApp.LoginForm.user + "/friends/" + Username + "/aes").Body.ToString().Trim(charsToTrim); string friendPublic = FbClient.Get(EncryptedMailApp.LoginForm.user + "/friends/" + Username + "/publicKey").Body.ToString().Trim(charsToTrim); string aes; string decryptedBody; string decryptedSubject; try { string decryptetaes = RSAobj.Decrypt(encryptedAES); aes = decryptetaes; } catch { aes = null; Console.WriteLine("error on decrypting aes "); } try { decryptedBody = AesCrypt.DecryptParam(encryptedBody, aes); } catch { decryptedBody = null; Console.WriteLine("error on decrpting body"); } try { decryptedSubject = AesCrypt.DecryptParam(m.Subject, aes); } catch { decryptedSubject = null; Console.WriteLine("error on decrpting subject"); } if (RSAobj.VerifySign(decryptedBody, sign, friendPublic) == true) { Console.WriteLine("match"); signed = true; } else { Console.WriteLine("missmatch"); signed = false; } if (messages[index, 0] == null) { messages[index, 0] = Username; messages[index, 1] = decryptedSubject; messages[index, 2] = decryptedBody; } listBox1.Items.Add(new ListItem { Name = "From: " + Username + " Subject: " + decryptedSubject, Value = index.ToString() }); index++; foreach (Attachment attachment in m.Attachments) { byte[] allBytes = new byte[attachment.ContentStream.Length]; int bytesread = attachment.ContentStream.Read(allBytes, 0, (int)attachment.ContentStream.Length); if (System.IO.Directory.Exists("data\\" + dir + "\\attachments") == false) { System.IO.Directory.CreateDirectory("data\\" + dir + "\\attachments"); } string destinationFile = "data\\" + dir + "\\attachments\\" + attachment.Name; BinaryWriter writer = new BinaryWriter(new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)); writer.Write(allBytes); writer.Close(); if (attachment.Name.EndsWith("crp")) { EncryptedMailApp.CryptoStuff.DecryptFile(password, destinationFile, destinationFile.Replace("crp", "")); } //MessageBox.Show("saved attachment at attachments, attachment count is : "+ m.Attachments.Count); } } this.listBox1.MouseDoubleClick += new MouseEventHandler(listBox1_MouseDoubleClick); } }); } catch (InvalidCredentialsException) { MessageBox.Show("The server rejected the supplied credentials."); } }
public async Task <IActionResult> Login([FromBody] SysAdminLogin parm) { var res = new ApiResult <string>() { statusCode = (int)ApiEnum.HttpRequestError }; try { //获得公钥私钥,解密 var rsaKey = await _cache.GetAsync <List <string> >($"LOGINKEY:{parm.lid}"); if (rsaKey == null) { res.message = "登录失败,请刷新浏览器再次登录"; return(Ok(res)); } //Ras解密密码 var ras = new RSACrypt(rsaKey[0], rsaKey[1]); parm.password = ras.Decrypt(parm.password); //获得用户登录限制次数 var configLoginCount = Convert.ToInt32(_config[KeyHelper.LOGINCOUNT]); //获得登录次数和过期时间 var loginConfig = await _cache.GetAsync <SysAdminLoginConfig>(KeyHelper.LOGINCOUNT) ?? new SysAdminLoginConfig(); if (loginConfig.Count != 0 && loginConfig.DelayMinute != null) { //说明存在过期时间,需要判断 if (DateTime.Now <= loginConfig.DelayMinute) { res.message = "您的登录以超过设定次数,请稍后再次登录~"; return(Ok(res)); } else { //已经过了登录的预设时间,重置登录配置参数 loginConfig.Count = 0; loginConfig.DelayMinute = null; } } #region 验证码 var captcha = new SimpleCaptcha(); if (!captcha.Validate(parm.code, parm.cid)) { res.message = "验证码错误"; res.statusCode = (int)ApiEnum.ParameterError; return(Ok(res)); } #endregion //查询登录结果 var dbres = await _adminService.LoginAsync(parm); if (dbres.statusCode != 200) { //增加登录次数 loginConfig.Count += 1; //登录的次数大于配置的次数,则提示过期时间 if (loginConfig.Count == configLoginCount) { var configDelayMinute = Convert.ToInt32(_config[KeyHelper.LOGINDELAYMINUTE]); //记录过期时间 loginConfig.DelayMinute = DateTime.Now.AddMinutes(configDelayMinute); res.message = "登录次数超过" + configLoginCount + "次,请" + configDelayMinute + "分钟后再次登录"; return(Ok(res)); } //记录登录次数,保存到session await _cache.SetAsync(KeyHelper.LOGINCOUNT, loginConfig); //提示用户错误和登录次数信息 res.message = dbres.message; return(Ok(res)); } var user = dbres.data.admin; var identity = new ClaimsPrincipal( new ClaimsIdentity(new[] { new Claim(ClaimTypes.PrimarySid, user.IsSystem.ToString()), new Claim(ClaimTypes.Sid, user.Guid), new Claim(ClaimTypes.Role, "授权用户"), new Claim(ClaimTypes.Name, user.TrueName), new Claim(ClaimTypes.WindowsAccountName, user.LoginName), new Claim(ClaimTypes.UserData, user.UpLoginDate.ToString()) }, CookieAuthenticationDefaults.AuthenticationScheme) ); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity); ////如果保存用户类型是Session,则默认设置cookie退出浏览器 清空 //if (_config[KeyHelper.LOGINSAVEUSER] == "Session") //{ // await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties // { // AllowRefresh = false // }); //} //else //{ // await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties // { // ExpiresUtc = DateTime.UtcNow.AddHours(_config.GetValue(KeyHelper.LOGINCOOKIEEXPIRES, 0.5D)), // IsPersistent = true, // AllowRefresh = false // }); //} //把权限存到缓存里 await _cache.SetAsync(KeyHelper.ADMINMENU + "_" + dbres.data.admin.Guid, dbres.data.menu); res.data = JwtHelper.IssueJWT(new TokenModel() { Uid = user.Guid, UserName = user.LoginName, Role = "Admin", TokenType = "Web" }); await _cache.RemoveAsync($"LOGINKEY:{parm.lid}"); await _cache.RemoveAsync(KeyHelper.LOGINCOUNT); #region 保存日志 var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { Guid = Guid.NewGuid().ToString(), Logged = DateTime.Now, Logger = LogEnum.LOGIN.GetEnumText(), Level = "Info", Message = "登录:" + parm.loginname, Callsite = "/fytadmin/login", IP = HttpContext.GetIP(), User = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); #endregion } catch (CryptographicException) { res.message = "登录失败,请刷新浏览器重试"; res.statusCode = (int)ApiEnum.Error; return(Ok(res)); } catch (Exception ex) { var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { Guid = Guid.NewGuid().ToString(), Logged = DateTime.Now, Logger = LogEnum.LOGIN.GetEnumText(), Level = "Error", Message = "登录失败!" + ex.Message, Exception = ex.ToString(), Callsite = "/fytadmin/login", IP = HttpContext.GetIP(), User = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); res.message = "登录失败,请刷新浏览器重试"; res.statusCode = (int)ApiEnum.Error; return(Ok(res)); } res.statusCode = (int)ApiEnum.Status; return(Ok(res)); }