private void buttonSend_Click(object sender, RoutedEventArgs e) { if (!(textBoxMessage.Text.Length == 0)) { Message message = new Message(); message.Date = DateTime.Now; //message.EncryptedText = textBoxMessage.Text; message.Receiver = _receiver; message.Sender = _user; using (Aes myAes = Aes.Create()) { byte[] encrypted = AESUtility.EncryptStringToBytes_Aes(textBoxMessage.Text, myAes.Key, myAes.IV); message.EncryptedText = encrypted; message.IV = myAes.IV; message.EncryptedAesKey = RSAUtility.RSAEncrypt(_receiver.PublicKey, myAes.Key); } //Generate hash from original message & encrypted with RSA for signing message.RSAEncryptedHashedMessage = RSAUtility.RSASign(_user.PrivateKey, Encoding.ASCII.GetBytes(textBoxMessage.Text)); _messageRepository.InsertMessage(message); textBoxMessage.Text = ""; LoadConversations(); } }
private void LoadConversations() { List <Message> messages = _messageRepository.GetAConversation(_user, _receiver); textBlockMessages.Text = ""; foreach (Message message in messages) { string decryptedText = AESUtility.DecryptStringFromBytes_Aes(message.EncryptedText, RSAUtility.RSADecrypt(message.Receiver.PrivateKey, message.EncryptedAesKey), message.IV); if (RSAUtility.RSAVerifySignedHash(Encoding.ASCII.GetBytes(decryptedText), message.RSAEncryptedHashedMessage, message.Sender.PublicKey)) { textBlockMessages.Text += message.Date.ToString("F") + "\n" + message.Sender.Username + ": " + decryptedText + "\n\n"; } else { MessageBox.Show("Error, someone tries to mess with the keys.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } scrollviewerConversation.ScrollToEnd(); }
public ActionResult RSA(RSAViewModel model) { RSAViewModel viewModel = RSAUtility.rsa2(model); ModelState.Clear(); return(View(viewModel)); }
private string signData(HttpWebRequest request, byte[] request_data = null) { System.IO.MemoryStream output = new System.IO.MemoryStream(); //签名前以 换行符("\n") 拼接各个字段: // method+"\n"+uri+"\n"+query_string+"\n"+nonce+"\n"+timestamp+"\n"+Authorization+"\n"+request_data byte[] data = ToBytes(request.Method.ToLower()); output.Write(data, 0, data.Length); output.WriteByte((byte)'\n');//method string uri = request.RequestUri.AbsoluteUri; if (string.IsNullOrEmpty(uri)) { uri = ""; } int index = uri.IndexOf("/v1/"); if (index != -1) { uri = uri.Substring(index); } data = ToBytes(uri); output.Write(data, 0, data.Length); output.WriteByte((byte)'\n');//uri path data = ToBytes(request.RequestUri.Query); output.Write(data, 0, data.Length); output.WriteByte((byte)'\n');//query_string data = ToBytes(request.Headers[HEADER_KEY_NONCE]); output.Write(data, 0, data.Length); output.WriteByte((byte)'\n');//nonce data = ToBytes(request.Headers[HEADER_KEY_TIMESTAMP]); output.Write(data, 0, data.Length); output.WriteByte((byte)'\n');//timestamp data = ToBytes(request.Headers[HEADER_KEY_AUTHORIZATION]); output.Write(data, 0, data.Length); output.WriteByte((byte)'\n');//Authorization // request_data = new byte[1024]; if (request_data != null) { output.Write(request_data, 0, request_data.Length); } string toSignString = System.Text.Encoding.UTF8.GetString(output.ToArray()); output.Close(); Debug.WriteLine("要签名的字符串:" + toSignString); return(RSAUtility.Sign(toSignString, PRIVATE_KEY)); }
public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Id", Id); info.AddValue("Name", Name); // Encrypt using utility class. //info.AddValue("SSN", SSN); byte[] data = RSAUtility.Encrypt(SSN, cnxnString); info.AddValue("SSNEncrypt", data); info.AddValue("isDirty", isDirty); }
protected PersonComplexRSA(SerializationInfo info, StreamingContext context, string cnxnString) { Id = info.GetInt32("Id"); Name = info.GetString("Name"); // Decrypt using utility class SSNEncrypt = (byte[])info.GetValue("SSNEncrypt", typeof(byte[])); SSN = RSAUtility.Decrypt(SSNEncrypt, cnxnString); this.cnxnString = cnxnString; isDirty = info.GetBoolean("isDirty"); }
public async Task RSAGenerate(string message) { try { var model = new RSAViewModel(); model.PlainText = message; var result = RSAUtility.rsa2(model); await Clients.All.SendAsync("ReceiveMessage", result); } catch { await Clients.All.SendAsync("ReceiveMessage", "Invalid input"); } }
private void buttonRegister_Click(object sender, RoutedEventArgs e) { string username = textboxUsername.Text; string password = passwordBox.Password; string passwordRepeat = passwordBoxRepeat.Password; if (_userRepository.CheckIfUsernameAllreadyExists(username)) { MessageBox.Show("The user allready exists.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } else if (password != passwordRepeat) { MessageBox.Show("The repeated password isn't the same as the password", "Error", MessageBoxButton.OK, MessageBoxImage.Error); passwordBox.Password = ""; passwordBoxRepeat.Password = ""; } else if (password.Length <= 6) { MessageBox.Show("The password must have at least 7 characters..", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } else if (username.Length <= 3) { MessageBox.Show("The username must have at least 4 characters.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } else { User user = new User(); user.Username = username; user.Salt = HashUtility.GenerateSalt(); user.Password = HashUtility.GenerateSHA256FromString(password + user.Salt); List <string> keys = RSAUtility.GenerateRSAPublicAndPrivateKeys(); user.PublicKey = keys[0]; user.PrivateKey = keys[1]; _userRepository.AddUser(user); MessageBox.Show("Succesvol geregistreerd!"); tabControl.SelectedIndex = 0; } }
public IActionResult GetPublicKey() { var publicKey = _settings.PublicKey; try { RSACryptoServiceProvider publicProvider = new RSACryptoServiceProvider(); RSAUtility.FromXmlString(publicProvider, publicKey); var publicPemKey = new StringWriter(); RSAUtility.ExportPublicKey(publicProvider, publicPemKey); var key = new { Key = publicPemKey.ToString() }; return(Ok(key)); } catch (Exception ex) { return(Ok("There was an error Creating a public key")); } }
private Dictionary <string, string> verifyData(HttpWebResponse response) { Dictionary <string, string> result = new Dictionary <string, string>(); if (response.StatusCode != HttpStatusCode.OK) { throw new System.Exception("error code:" + response.StatusCode + ". message:" + response.StatusDescription); } string nonce = response.Headers[HEADER_KEY_NONCE] != null ? response.Headers[HEADER_KEY_NONCE] : ""; string timestamp = response.Headers[HEADER_KEY_TIMESTAMP] != null ? response.Headers[HEADER_KEY_TIMESTAMP] : ""; string secretKey = response.Headers[HEADER_KEY_AUTHORIZATION] != null ? response.Headers[HEADER_KEY_AUTHORIZATION] : ""; System.IO.MemoryStream output = new System.IO.MemoryStream(); byte[] data = this.ToBytes(nonce); output.Write(data, 0, data.Length); output.WriteByte((byte)'\n');//header data = this.ToBytes(timestamp); output.Write(data, 0, data.Length); output.WriteByte((byte)'\n');//header data = this.ToBytes(secretKey); output.Write(data, 0, data.Length); output.WriteByte((byte)'\n');//header System.IO.Stream stream = response.GetResponseStream(); StreamReader sr = new StreamReader(stream); string body = sr.ReadToEnd(); Console.WriteLine("响应的body:" + body); Debug.WriteLine("响应的body:" + body); data = this.ToBytes(body); output.Write(data, 0, data.Length); string verifyData = System.Text.Encoding.UTF8.GetString(output.ToArray()); string sign = response.Headers[PaymaxConfig.SIGN] != null ? response.Headers[PaymaxConfig.SIGN] : ""; bool flag = RSAUtility.Verify(verifyData, sign, PAYMAX_PUBLIC_KEY); if (!flag) { throw new InvalidResponseException("Invalid Response.[Response Data And Sign Verify Failure.]"); } if (!SECRET_KEY.Equals(secretKey)) { throw new InvalidResponseException("Invalid Response.[Secret Key Is Invalid.]"); } long currMillisenconds = ComUtility.ToMillisenconds(); if (long.Parse(timestamp) + VALID_RESPONSE_TTL < currMillisenconds) { throw new InvalidResponseException("Invalid Response.[Response Time Is Invalid.]"); } result = new Dictionary <string, string>(); result.Add(RESPONSE_CODE, response.StatusCode.ToString()); result.Add(RESPONSE_DATA, body); return(result); }
public RSACrypto(string pub_key) { mrsa = new RSACryptoServiceProvider(); mrsa.ImportParameters(RSAUtility.ConvertFromPemPublicKey(pub_key)); }
public IActionResult Login([FromBody] Login credentials) { if (credentials == null) { return(BadRequest("Invalid Request")); } try { var privateKey = _settings.PrivateKey; var encryptedUser = Convert.FromBase64String(credentials.UserName); var encryptedPass = Convert.FromBase64String(credentials.Password); RSACryptoServiceProvider privateProvider = new RSACryptoServiceProvider(); RSAUtility.FromXmlString(privateProvider, privateKey); var decryptedUser = privateProvider.Decrypt(encryptedUser, false); var decryptedPass = privateProvider.Decrypt(encryptedPass, false); var plaintextUser = Encoding.ASCII.GetString(decryptedUser); var plaintextPass = Encoding.ASCII.GetString(decryptedPass); // See if the user exists var user = _context.Users .Where(u => (u.Username == plaintextUser || u.Email == plaintextUser) && u.IsDeleted == false) .FirstOrDefault(); // Decrypt the database password var dbPassBytes = user != null ? Convert.FromBase64String(user.Password) : null; var decryptedDbPass = dbPassBytes != null ? privateProvider.Decrypt(dbPassBytes, false) : null; var plainTextDbPass = decryptedDbPass != null ? Encoding.ASCII.GetString(decryptedDbPass) : null; // Return bad request if user doesn't exist, or password is expired if (user == null) { return(Ok(new { Message = "User not found" })); } else if (user.PasswordExpiration < DateTime.Now) { return(Ok(new { Message = "Password Expired" })); } else if (plainTextDbPass != plaintextPass) { return(Ok(new { Message = "Username or Password is incorrect" })); } else { var secretKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_settings.SecretKey)); var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); var role = _context.Roles .Where(r => r.RoleId == user.RoleId) .FirstOrDefault(); // Add specific claims var claims = new List <Claim> { new Claim("User", $"{user.FirstName} {user.LastName}"), new Claim("Role", role.Name) }; var userClaimMaps = _context.UserRoleClaimMaps .Where(map => map.RoleId == user.RoleId) .ToList(); foreach (var claim in userClaimMaps) { var currentClaim = _context.Claims .Where(c => c.ClaimId == claim.ClaimId) .FirstOrDefault(); claims.Add(new Claim("Claim", currentClaim.Name)); } // Create the token options var tokenOptions = new JwtSecurityToken( issuer: _settings.Issuer, audience: _settings.Audience, claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: signingCredentials ); var handler = new JwtSecurityTokenHandler(); var tokenString = handler.WriteToken(tokenOptions); //Set last logon for user user.LastLogon = DateTime.Now; user.Modified = DateTime.Now; _context.SaveChanges(); return(Ok(new { Token = tokenString })); } } catch (Exception ex) { return(Ok(ex.Message)); } }