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)); }
public void OnGet() { Number = Utils.Number(15); RsaKey = RSACrypt.GetKey(); //获得公钥和私钥 MemoryCacheService.Default.SetCache("LOGINKEY_" + Number, RsaKey, 5); }
static void Main(string[] args) { var r = new RSACrypt(); var a = ""; var b = ""; r.RSAKey(out a, out b); System.Console.ReadKey(); }
/// <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 OnGet() { RsaKey = RSACrypt.GetKey(); var auth = HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); //auth.Result.Succeeded; if (auth.Status.ToString() != "Faulted") { RedirectToPage("Index"); } }
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); } }
public ActionResult Login() { var auth = HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); //auth.Result.Succeeded; if (auth.Status.ToString() != "Faulted") { RedirectToPage("Index"); } List <string> RsaKey = RSACrypt.GetKey(); return(View(RsaKey)); }
public void OnGet() { var auth = HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); //auth.Result.Succeeded; if (auth.Status.ToString() != "Faulted") { RedirectToPage("Index"); } RsaKey = RSACrypt.GetKey(); //获得公钥和私钥 MemoryCacheService.Default.SetCache("LOGINKEY", RsaKey); }
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 IActionResult Login(string userName, string password, string privateKey, string publicKey) { var apiRes = new ApiResult <SysUserInfo>(); var token = ""; //Ras解密密码 var ras = new RSACrypt(privateKey, publicKey); var loginmodel = _sysUserInfoService.GetModelAsync(c => c.loginName == userName); if (loginmodel == null) { } return(null); }
public ApiResult LoadLoginInfo() { var rsaKey = RSACrypt.GetKey(); var number = Guid.NewGuid().ToString(); if (rsaKey.Count <= 0 || rsaKey == null) { throw new ArgumentNullException("获取登录的公钥和私钥为空"); } //获得公钥和私钥 _cache.Set("LOGINKEY" + number, rsaKey); return(new ApiResult(data: new { RsaKey = rsaKey, Number = number })); }
private void LoadKey() { var rsaKey = RSACrypt.GetKey(); var number = Guid.NewGuid().ToString(); if (rsaKey.Count <= 0 || rsaKey == null) { throw new ArgumentNullException("»ñÈ¡µÇ¼µÄ¹«Ô¿ºÍ˽ԿΪ¿Õ"); } RsaKey = rsaKey; Number = number; //»ñµÃ¹«Ô¿ºÍ˽Կ _cache.Set(LoginKey + number, rsaKey); }
public async Task OnGetAsync() { var auth = HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); if (auth.Status.ToString() != "Faulted") { RedirectToPage("Index"); } RsaKey = RSACrypt.GetKey(); lid = Guid.NewGuid(); //获得公钥和私钥 await _cache.SetAsync($"LOGINKEY:{lid}", RsaKey, expirationMinute : 30); }
private void registerbtn_Click(object sender, EventArgs e) { if (usrname.Text.Length < 4 && usrpass.Text.Length < 4) { MessageBox.Show("Username or Password is invalid."); } else { RSACrypt RSAobj = RSACrypt.getInstance(); RSAobj.createKey(); string dir = usrname.Text; Directory.CreateDirectory("data\\" + dir); var sw = new StreamWriter("data\\" + dir + "\\data.ls"); string encusr = AesCrypt.Encrypt(usrname.Text); string encpass = AesCrypt.Encrypt(usrpass.Text); sw.WriteLine(encusr); sw.WriteLine(encpass); sw.Close(); var sw2 = new StreamWriter("data\\" + dir + "\\PublicKey.ls"); string PublicKey = RSAobj.RSApublicKey; //string PublicKey = new string(RSAobj.PublicKey.Where(c => !char.IsWhiteSpace(c)).ToArray()); sw2.WriteLine(PublicKey); sw2.Close(); var sw3 = new StreamWriter("data\\" + dir + "\\PrivateKey.ls"); //string PrivateKey = new string(RSAobj.PrivateKey.Where(c => !char.IsWhiteSpace(c)).ToArray()); string PrivateKey = RSAobj.PrivateKey; sw3.WriteLine(PrivateKey); sw3.Close(); var sw4 = new StreamWriter("data\\" + dir + "\\mail.ls"); string UserMail = AesCrypt.Encrypt(UserMailTextBox.Text); string UserMailPass = AesCrypt.Encrypt(UserMailPassBox.Text); sw4.WriteLine(UserMail); sw4.WriteLine(UserMailPass); sw4.Close(); RgClient.Set(usrname.Text + "/publicKey", PublicKey); RgClient.Set(usrname.Text + "/mail", UserMailTextBox.Text); MessageBox.Show("Registration successful.", usrname.Text); this.Close(); } }
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 ImportModules() { // TODO: WORK PATH BELOW rootPath = @"D:\OOP\OOP\Lab1\PictureDraw\Modules"; modules = new List <Assembly>(); var directory = new DirectoryInfo(rootPath); foreach (var file in directory.GetFiles("*.dll")) { try { if (RSACrypt.VerifySignedHash(File.ReadAllBytes(file.FullName), File.ReadAllText(@"G:\public.xml"))) { modules.Add(Assembly.LoadFrom(file.FullName)); } } catch { MessageBox.Show($@"Sorry, but {rootPath}\{file} was damaged. Please, fix or remove it.", "Load error", MessageBoxButton.OK, MessageBoxImage.Error); } } }
private void button1_Click(object sender, EventArgs e) { RSACrypt crypt = new RSACrypt(); var result = crypt.AssignNewKey(); }
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> 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)); }
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)); } }