// В цикле while ждём новых сообщений от сервера (обрабатываются в case) private void GetNewMessages() { MessageClass message; try { while (true) { message = GetFromStream(ref client); switch (message.code) { // При получении публичного ключа сервера сохраняем его case codes.PUBLIC_KEY: buttonSend.Invoke(new Action(() => buttonSend.Enabled = true)); serverKey = JsonConvert.DeserializeObject <RSAParameters>(message.info); break; // При получении зашифрованного сервером сообщения расшифровываем и выводиим в два поля case codes.ENCRYPTED_MESSAGE: textEncrypt.Text = message.info; textDecrypt.Text = rs.Decrypt(message.info); break; } } } catch (Exception e) { MessageBox.Show("In GetNewMessages: " + e.Message); } }
public override void OnActionExecuting(HttpActionContext actionContext) { string token; try { token = actionContext.Request.Headers.GetValues("Authorization-Token").First(); } catch (Exception) { actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest) { Content = new StringContent("Missing Authorization-Token") }; return; } try { //This part is where you verify the incoming token AuthorizedUserRepository.GetUsers().First(x => x.Name == RSAClass.Decrypt(token)); base.OnActionExecuting(actionContext); } catch (Exception) { actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden) { Content = new StringContent("Unauthorized User") }; return; } }
public ActionResult Delete(int id, string token) { if (RSAClass.Decrypt(token) == "token") { employeeDB.deleteEmployee(id); } return(BadRequest()); }
public ActionResult Put([FromBody] Employee emp, string token) { if (RSAClass.Decrypt(token) == "token") { employeeDB.updateEmployee(emp); } return(BadRequest()); }
public ActionResult <Employee> Get(int id, string token) { if (RSAClass.Decrypt(token) == "token") { return(employeeDB.getEmployeeByID(id)); } return(BadRequest()); }
public ActionResult <IEnumerable <Employee> > Get(string token) { if (RSAClass.Decrypt(token) == "token") { return(employeeDB.getAllEmployee().ToList()); } return(BadRequest()); }
public void RSAParameters() { var token = "abundatrade"; var encrypted = RSAClass.Encrypt(token); var decrypted = RSAClass.Decrypt(encrypted); Assert.AreEqual(token, decrypted); }
public void VerifyToken() { var token = "User1"; var encryptedToken = RSAClass.Encrypt(token); var decryptedToken = RSAClass.Decrypt(encryptedToken); Console.WriteLine(encryptedToken); Assert.Equal(token, decryptedToken); }
public void RSATest() { var message = "this is a test"; RSAClass.GenerateKey(); byte[] rsaEncrypted = RSAClass.Encrypt(Encoding.UTF8.GetBytes(message)); byte[] rsaDecrypted = RSAClass.Decrypt(rsaEncrypted); Console.WriteLine("Original: " + message + "\n"); Console.WriteLine("Encrypted: " + BitConverter.ToString(rsaEncrypted) + "\n"); Console.WriteLine("Decrypted: " + Encoding.UTF8.GetString(rsaDecrypted)); }
/// <summary> /// /// </summary> /// <param name="token">Hexadecimal string from client</param> /// <returns></returns> public IUser GetByAuthorisationToken(string token) { try { var tokenByteArray = SoapHexBinary.Parse(token).Value; var decryptedClientUser = RSAClass.Decrypt(tokenByteArray); var user = Get(decryptedClientUser.UserId); return(user); } catch (Exception ex) { throw ex; } }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { try { var token = context.ActionContext.Request.Headers.GetValues("Authorisation-Token").First(); var tokenByteArray = SoapHexBinary.Parse(token).Value; var decryptedClientUser = RSAClass.Decrypt(tokenByteArray); return(Task.FromResult(0)); } catch (Exception ex) { // Log to db context.ErrorResult = new AuthenticationFailureResponse("Authentication failure", context.Request); return(Task.FromResult(0)); } }
/// <summary> /// Validates a validation token /// </summary> /// <param name="actionContext">The context to execute</param> /// <param name="ip">The ip address to verify against</param> private void ValidateToken(HttpActionContext actionContext, string ip) { string token; try { token = actionContext.Request.Headers.GetValues("Authorization-Token").First(); } catch (Exception) { actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest) { Content = new StringContent(@"{""error"": ""Missing Authorization-Token""}") }; return; } try { bool allowed = false; using (var context = new DataBaseDataContext()) { allowed = (from ev in context.KeyRestrictions where ev.ApiKey.key == RSAClass.Decrypt(token) && ev.Allowed == true && (ev.IPAddress == ip || ev.IPAddress == "*") select ev).Count() > 0; } if (!allowed) { actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden) { Content = new StringContent(@"{""error"": ""Unauthorized IP Address""}") }; } base.OnActionExecuting(actionContext); } catch (Exception) { actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden) { Content = new StringContent(@"{""error"": ""Unauthorized User""}") }; return; } }
protected override Task <HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { try { if (!request.Headers.Contains("Authorization-Token")) { return(Task <HttpResponseMessage> .Factory.StartNew(() => { return new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("You need to include Authorization-Token") }; })); } var token = request.Headers.GetValues("Authorization-Token").FirstOrDefault(); if (string.IsNullOrEmpty(token)) { return(Task <HttpResponseMessage> .Factory.StartNew(() => { return new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("Missing Authorization-Token") }; })); } var decryptedToken = RSAClass.Decrypt(token); // TODO: do your query to find the user var user = decryptedToken; var identity = new GenericIdentity(decryptedToken); string[] roles = new[] { "Users", "Testers" }; var principal = new GenericPrincipal(identity, roles); Thread.CurrentPrincipal = principal; } catch { return(Task <HttpResponseMessage> .Factory.StartNew(() => { return new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("Error encountered in authorization token") }; })); } return(base.SendAsync(request, cancellationToken)); }
public override void OnActionExecuting(HttpActionContext actionContext) { string token; try { // 首先判断请求是否包含了Token,如果没有包含可返回异常请求信息 if (actionContext.Request.Headers.Contains(RQUESTHEADERTOKENKEY)) { token = actionContext.Request.Headers.GetValues(RQUESTHEADERTOKENKEY).First(); string authSiteID = actionContext.Request.Headers.GetValues(AUTHSITEID).First(); string authSite = actionContext.Request.Headers.GetValues(AUTHSITE).First();/// TODO:这里还可以对授权站点进行验证 // 验证Token是否正确 if (RSAClass.Decrypt(token) == (authSite + authSiteID + DateTime.Now.ToString("yyyyMMdd"))) { base.OnActionExecuting(actionContext); } else { // 验证失败 actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden) { Content = new StringContent("Unauthorized Site") }; return; } } else { // 验证失败 actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden) { Content = new StringContent("Unauthorized Site") }; return; } } catch (Exception) { actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest) { Content = new StringContent("Missing Authorization-Token") }; return; } }
// Обработка запросов от пользователя. При получении пакета с кодом disconnect прекращаем private void Process_User(ref TcpClient client, int id) { bool connected = true; try { MessageClass message; while (connected) { message = GetFromStream(ref client); switch (message.code) { // При получении публичного ключа отсылаем свой. case codes.PUBLIC_KEY: connectedUsers[id] = JsonConvert.DeserializeObject <RSAParameters>(message.info); // Вывод значений в textbox-формы textDecrypt.BeginInvoke(new Action(() => textDecrypt.Text = "Sent to user " + id)); textStatus.BeginInvoke(new Action(() => textStatus.Text = message.info)); SendToStream(new MessageClass(codes.PUBLIC_KEY, rs.PublicKeyString()), ref client); break; // При получении зашифрованного сообщения расшифровываем своим приватным ключом, добавляем текст, // шифруем и отсылаем case codes.ENCRYPTED_MESSAGE: textDecrypt.Text = message.info; SendToStream(new MessageClass(codes.ENCRYPTED_MESSAGE, rs.Encrypt("Пажилое сообщение: " + rs.Decrypt(message.info), connectedUsers[id])), ref client); break; // Удаляем пользователя, захотевшего уйти case codes.DISCONNECT_MESSAGE: connectedUsers.Remove(id); connected = false; break; } } } catch (Exception e) { MessageBox.Show("In Process_User: " + e.Message); } }