public void RasEncryptTest() { RSAEncrypt Rsa = new RSAEncrypt(); Rsa.GenerateKeys("d://pems"); string s = "王进锋"; string s1 = "jfwang123"; var spwd = Rsa.Encrypt(s, "d://pems/RSA.Pub"); var s1pwd = Rsa.Encrypt(s1, "d://pems/RSA.Pub"); Assert.Equal(Rsa.Decrypt(spwd, "d://pems/RSA.Private"), s); Assert.Equal(Rsa.Decrypt(s1pwd, "d://pems/RSA.Private"), s1); }
public void Encrypt(string val) { //RSACryptoServiceProvider oRSA = new RSACryptoServiceProvider(); //string privatekey = oRSA.ToXmlString(true);//私钥 //string publickey = oRSA.ToXmlString(false);//公钥 ////这两个密钥需要保存下来 //byte[] messagebytes = Encoding.UTF8.GetBytes(val); //需要加密的数据 ////公钥加密 //RSACryptoServiceProvider oRSA1 = new RSACryptoServiceProvider(); //oRSA1.FromXmlString(publickey); //加密要用到公钥所以导入公钥 //byte[] AOutput = oRSA1.Encrypt(messagebytes, false); //AOutput 加密以后的数据 var str = RSAEncrypt.Encrypt(val); Console.WriteLine(str); str = RSAEncrypt.Decrypt(val); Console.WriteLine(str); }
public Task CreateValueProviderAsync(ValueProviderFactoryContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var request = context.ActionContext.HttpContext.Request; WebParams webParams = new WebParams(request); string encryptKey = "__encryptdata"; string encryptData = request.Query.ContainsKey(encryptKey) ? request.Query[encryptKey].ToString() : string.Empty; if (encryptData.IsNullOrEmpty() && request.HasFormContentType) { encryptData = request.Form[encryptKey]; } bool isEncryptDatas = webParams.ContainsKey(encryptKey); bool isDecryptSucceed = false; Exception decryptException = null; IDictionary <string, string> dicDecryptDatas = new Dictionary <string, string>(); if (encryptData.IsNotNullOrEmpty()) { try { //生成密钥 //string rsaKey = RSAEncrypt.GenerateKey(); string rsaKey = IFConfigReader.RSAPrivateKey; //通过密钥创建对象 RSAEncrypt privateRSA = new RSAEncrypt(rsaKey); //解密 string decryptData = privateRSA.Decrypt(encryptData); //导出公钥 //string publicKey = privateRSA.ExportParameters(false); //通过公钥加密 //RSAEncrypt publicRSA = new RSAEncrypt(publicKey); foreach (var item in decryptData.Split('&')) { string[] values = item.Split('='); dicDecryptDatas.Add(values[0], values[1]); } isDecryptSucceed = true; } catch (Exception ex) { decryptException = ex; isDecryptSucceed = false; } if (dicDecryptDatas.Count() > 0) { AddResultsToHttpContext(context, isEncryptDatas, isDecryptSucceed, decryptException, dicDecryptDatas); return(AddValueProviderAsync(context, dicDecryptDatas)); } } AddResultsToHttpContext(context, isEncryptDatas, isDecryptSucceed, decryptException, dicDecryptDatas); return(TaskCache.CompletedTask); }
public async Task <ApiResult <string> > Login([FromBody] SysAdminLogin parm) { var apiRes = new ApiResult <string>() { statusCode = (int)ApiEnum.HttpRequestError }; var token = ""; try { #region 1. 从缓存获取公钥私钥解密,再解密密码 //获得公钥私钥,解密 var rsaKey = MemoryCacheHelper.Get <List <string> >(KeyModel.LoginKey); if (rsaKey == null) { apiRes.msg = "登录失败,请刷新浏览器再次登录"; return(apiRes); } //Ras解密密码 var ras = new RSAEncrypt(rsaKey[0], rsaKey[1]); parm.password = ras.Decrypt(parm.password); #endregion #region 2. 判断用户登录次数限制以及过期时间 //获得用户登录限制次数 var configLoginCount = Convert.ToInt32(Appsettings.Configuration[KeyModel.LoginCount]); //获得登录次数和过期时间 SysAdminLoginConfig loginConfig = MemoryCacheHelper.Get <SysAdminLoginConfig>(KeyModel.LoginCount) ?? new SysAdminLoginConfig(); if (loginConfig.Count != 0 && loginConfig.DelayMinute != null) { //说明存在过期时间,需要判断 if (DateTime.Now <= loginConfig.DelayMinute) { apiRes.msg = "您的登录以超过设定次数,请稍后再次登录~"; return(apiRes); } else { //已经过了登录的预设时间,重置登录配置参数 loginConfig.Count = 0; loginConfig.DelayMinute = null; } } #endregion #region 3. 从数据库查询该用户 //查询登录结果 var dbres = _adminService.LoginAsync(parm).Result; if (dbres.statusCode != 200) { //增加登录次数 loginConfig.Count += 1; //登录的次数大于配置的次数,则提示过期时间 if (loginConfig.Count == configLoginCount) { var configDelayMinute = Convert.ToInt32(Appsettings.Configuration[KeyModel.LogindElayMinute]); //记录过期时间 loginConfig.DelayMinute = DateTime.Now.AddMinutes(configDelayMinute); apiRes.msg = "登录次数超过" + configLoginCount + "次,请" + configDelayMinute + "分钟后再次登录"; return(apiRes); } //记录登录次数,保存到session MemoryCacheHelper.Set(KeyModel.LoginCount, loginConfig); //提示用户错误和登录次数信息 apiRes.msg = dbres.msg + " 您还剩余" + (configLoginCount - loginConfig.Count) + "登录次数"; return(apiRes); } #endregion #region 4. 设置Identity User信息 var user = dbres.data.admin; var identity = new ClaimsPrincipal( new ClaimsIdentity(new[] { new Claim(ClaimTypes.Sid, user.ID), new Claim(ClaimTypes.Role, user.RoleId), new Claim(ClaimTypes.Thumbprint, user.HeadPic), new Claim(ClaimTypes.Name, user.RelName), new Claim(ClaimTypes.WindowsAccountName, user.Account), new Claim(ClaimTypes.UserData, user.LastLoginTime.ToString()) }, CookieAuthenticationDefaults.AuthenticationScheme) ); if (Appsettings.Configuration[KeyModel.LoginSaveUser] == "Session") {//如果保存用户类型是Session,则默认设置cookie退出浏览器 清空,并且保存用户信息 await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties { AllowRefresh = false }); } else { //根据配置保存浏览器用户信息,小时单位 var hours = int.Parse(Appsettings.Configuration[KeyModel.LoginCookieExpires]); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddHours(hours), IsPersistent = true, AllowRefresh = false }); } #endregion #region 5. 保存权限信息到缓存 if (dbres.data.menu != null) { var menuSaveType = Appsettings.Configuration[KeyModel.LoginAuthorize]; if (menuSaveType == "Redis") { RedisCacheHelper.Set(KeyModel.AdminMenu + "_" + dbres.data.admin.ID, dbres.data.menu); } else { MemoryCacheHelper.Set(KeyModel.AdminMenu + "_" + dbres.data.admin.ID, dbres.data.menu); } } #endregion #region 6. 生成token信息,并且返回给前端 token = JwtHelper.IssueToken(new TokenModel() { UserID = user.ID, UserName = user.RelName, UserAccount = user.Account, Role = "AdminPolicy", ProjectName = "DL.Admin" }); MemoryCacheHelper.Del <string>(KeyModel.LoginKey); MemoryCacheHelper.Del <string>(KeyModel.LoginCount); #endregion #region 7. 保存日志 var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { ID = Guid.NewGuid().ToString(), CreateTime = DateTime.Now, Layer = 1, Message = "登录", Url = "/Login/Login", IP = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(), Account = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); #endregion } catch (Exception ex) { apiRes.msg = ex.Message; apiRes.statusCode = (int)ApiEnum.Error; #region 保存日志 var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { ID = Guid.NewGuid().ToString(), CreateTime = DateTime.Now, Layer = 4, Message = "登录失败!" + ex.Message, Exception = ex.Message, Url = "/Login/Login", IP = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(), Account = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); #endregion } apiRes.statusCode = (int)ApiEnum.Status; apiRes.data = token; return(apiRes); }
public static void HandleClients(TcpClient client) { string publicKey; string privateKey; int KeySize = 2048; RSAEncrypt.GenerateKeys(KeySize, out publicKey, out privateKey); while (true) { if (client.Available > 0) { // Setup reader/writer stream NetworkStream stream = client.GetStream(); StreamReader Reader = new StreamReader(stream); StreamWriter Writer = new StreamWriter(stream) { AutoFlush = true }; string data = Reader.ReadLine(); ChatUser chatUser = JsonConvert.DeserializeObject <ChatUser>(data); if (chatUser.CommandInter == (int)ChatUser.Command.getRSAKey) { chatUser.RsaKey = publicKey; list_clients.TryAdd(chatUser.ChatUserId, client); chatUsers.Add(chatUser); stream = list_clients[chatUser.ChatUserId].GetStream(); string Input = JsonConvert.SerializeObject(chatUser); Writer.WriteLine(Input); } else if (chatUser.CommandInter == (int)ChatUser.Command.AddChatUser) { chatUser.DesKey = RSAEncrypt.Decrypt(chatUser.DesKey, KeySize, publicKey); client = list_clients[chatUser.ChatUserId]; Console.WriteLine(chatUser.User.UserName + " entrou na sala " + chatUser.Chat.Name + "!"); chatUser.Message = Encrypt(chatUser.User.UserName + " entrou na sala " + chatUser.Chat.Name + "!", chatUser.DesKey); Broadcast(chatUser); } else if (chatUser.CommandInter == (int)ChatUser.Command.DeleteChatUser) { client.Client.Shutdown(SocketShutdown.Both); client.Close(); TcpClient tcpRemove; list_clients.TryRemove(chatUser.ChatUserId, out tcpRemove); ChatUser userToRemove = chatUsers.Find(c => c.ChatUserId == chatUser.ChatUserId); chatUsers.Remove(userToRemove); Console.WriteLine(chatUser.User.UserName + " saiu da sala " + chatUser.Chat.Name + "!"); chatUser.Message = Encrypt(chatUser.User.UserName + " saiu da sala " + chatUser.Chat.Name + "!", chatUser.DesKey); Broadcast(chatUser); break; } else if (chatUser.CommandInter == (int)ChatUser.Command.SendMessage) { // Decrypt the bytes to a string. string messageDecrypted = Decrypt(chatUser.Message, chatUser.DesKey); Console.WriteLine("Sala: " + chatUser.Chat.Name + "-" + chatUser.User.UserName + ": " + messageDecrypted); Broadcast(chatUser); } } } }