// Return true if key was restored from message history. private static bool TryToRestoreKeyFromDialog(ref Dialog dialog) { if (dialog.Messages.Count <= 0) { return(false); } // Find message in collection with type Message.ExchangeKey. var exchangeMessageQuery = (from Message m in dialog.Messages where m.Type == MessageType.KeyExchange select m); IEnumerable <Message> messageQueryList = exchangeMessageQuery.ToList(); if (!messageQueryList.Any()) { return(false); } var isSentByMe = false; // Change if find exchange message from current user. foreach (var message in messageQueryList) { if (message.SenderUuid == AppUser.GetInstance().Uuid) { isSentByMe = true; // But current user cannot decipher this message because it is encrypted by another user public key. } else { var privateKey = AppUser.GetInstance().PrivateKeyXml; // Decrypt symmetric key. var temp = message; // `message` variable is immutable. if (DecryptMessageByAsymmetricAlgorithm(ref temp, privateKey)) { // Load AES key. dialog.Key = AesKey.FromJsonString(temp.Body); } } } if (dialog.Key == null) { return(false); } Logger.Info("AES key was restored from dialog with {0}.", dialog.Partner.Login); // If message sent by current user only, there is no way to restore key. // Otherwise if key was restored but was not send back to another user, current user have to do that. if (!isSentByMe) { SendKeyExchangeMessage(dialog); Logger.Info("AES key was sent back to the dialog with {0}.", dialog.Partner.Login); } return(true); }