void OnConnected(SocketArgs args) { if (m_SocketArgs != args) { return; } var kiv = AesKeyIV.GenKeyIV(); AesKeyIV.SendAesKeyIVRsa(args.m_Socket, args.m_RsaPub, kiv); new AesKeyIVAes(args, KIVHandleConnected, KIVHandleClose, kiv); }
public void _DisconnectAndCleanUp() { if (Tcp?.Client?.Connected == true) { Tcp.Client.Shutdown(SocketShutdown.Both); } Tcp?.Close(); Tcp = null; WholeMessage = null; _sharedPasscode = null; _sharedSymmetricKey = null; }
/// <summary> /// Decrypt the string with the aesKeyIV. /// </summary> /// <param name="encryptedString">The string to decrypt.</param> /// <param name="aesKeyIV">The Key and IV to decryipt with.</param> public static string DecryptWithAesKeyIV(string encryptedString, AesKeyIV aesKeyIV) { var aes = new AesManaged { IV = aesKeyIV.IV, Key = aesKeyIV.Key, Mode = CipherMode.CBC }; var encryptedBytes = Convert.FromBase64String(encryptedString); using (var decryptor = aes.CreateDecryptor()) { var stream = new MemoryStream(); var cs = new CryptoStream(stream, decryptor, CryptoStreamMode.Write); cs.Write(encryptedBytes, 0, encryptedBytes.Length); cs.Close(); return(Encoding.UTF8.GetString(stream.ToArray())); } }
/// <summary> /// Encrypt the string with the aesKeyIV. /// </summary> /// <param name="json">The string to encrypt.</param> /// <param name="aesKeyIV">The Key and IV to encrypt with.</param> public static string EncryptWithAesKeyIV(string json, AesKeyIV aesKeyIV) { var aes = new AesManaged { IV = aesKeyIV.IV, Key = aesKeyIV.Key, Mode = CipherMode.CBC }; var jsonBytes = Encoding.UTF8.GetBytes(json); using (var encryptor = aes.CreateEncryptor()) { var stream = new MemoryStream(); var cs = new CryptoStream(stream, encryptor, CryptoStreamMode.Write); cs.Write(jsonBytes, 0, jsonBytes.Length); cs.Close(); return(Convert.ToBase64String(stream.ToArray())); } }
public void ReceiveCallback(IAsyncResult result) { try { // Check how much bytes are received and call EndReceive to finalize handshake var received = Tcp.Client.EndReceive(result); // If we have received nothing then leave. if (received <= 0) { return; } // Copy the recieved data into new buffer , to avoid null bytes var recData = new byte[received]; Buffer.BlockCopy(ReceiveBuffer, 0, recData, 0, received); var encryptedString = Encoding.UTF8.GetString(recData); WholeMessage = string.IsNullOrWhiteSpace(WholeMessage) ? encryptedString : WholeMessage + encryptedString; // This is the reply to the start of the interaction. // If we can decrypt here, then we send back the _sym // key we will be using to encrypt our messages. if (WholeMessage.EndsWith("<BEG>")) { WholeMessage = WholeMessage.Replace("<BEG>", ""); var decryptedString = Crypto.DecryptWithAesKeyIV(WholeMessage, Crypto.CreateAesKeyIV(_sharedPasscode)); var publicKey = PublicKey.FromJson(new JSONObject(decryptedString)); // Send a new AES Symmetric key for using! _sharedSymmetricKey = Crypto.CreateAesKeyIV(); var encryptedWithTheirPublicKey = Crypto.EncryptWithPublicKey( publicKey.ToRsaParameters(), System.Text.Encoding.UTF8.GetBytes(_sharedSymmetricKey.ToJson().ToString())); Task.Run(async() => await StartConversation(Convert.ToBase64String(encryptedWithTheirPublicKey) + "<END>")); WholeMessage = null; } else if (WholeMessage.EndsWith("<TAC>")) { // The computer asked for the client list... // we shall send it to them encrypted! var contacts = Contact.GetAllContacts(this); var jsonArray = ContactInfo.ToJsonArray(contacts); var encrypted = Crypto.EncryptWithAesKeyIV(jsonArray.ToString(), _sharedSymmetricKey); var msg = Encoding.UTF8.GetBytes(encrypted + "<TAC>"); Task.Run(async() => await Tcp.Client.SendAsync(new ArraySegment <byte>(msg), SocketFlags.None)); WholeMessage = null; } else if (WholeMessage.EndsWith("<EOF>")) { // This is an encrypted message from the computer. WholeMessage = WholeMessage.Replace("<EOF>", ""); var decryptedString = Crypto.DecryptWithAesKeyIV(WholeMessage, _sharedSymmetricKey); var payload = TcpPayload.FromJson(new JSONObject(decryptedString)); if (!string.IsNullOrWhiteSpace(payload.Contact.PhoneNumber) && !string.IsNullOrWhiteSpace(payload.Message)) { // TODO Possible send delay so we don't overload the sms manager? Sms.SendTo(payload.Contact.PhoneNumber, payload.Message); } else { // Log an issue... } WholeMessage = null; } // Start receiving again Tcp.Client.BeginReceive(ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, ReceiveCallback, null); } catch (SocketException ex) { Android.Util.Log.Error("Receive Callback", ex.Message); OnDestroy(); } catch (Exception ex) { Android.Util.Log.Error("Receive Callback", ex.Message); // Clear the whole message WholeMessage = null; // Start receiving again if (Tcp != null && Tcp.Client != null) { Tcp.Client.BeginReceive(ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, ReceiveCallback, null); } } }