Skip to content

Secure Messaging with Socket and WebSocket: Bob, Alice, and Patrick Integration #2

Description

@c0d3sw0t

Secure Messaging with Socket and WebSocket: Bob, Alice, and Patrick Integration

This documentation provides a detailed guide on how to implement secure messaging using Sockets and WebSockets in a Flutter client app (Alice) and a server app (Bob). Additionally, it covers integrating a third client (Patrick) into the communication network.


Table of Contents

  1. Overview
  2. Requirements
  3. Architecture
  4. Setting Up the Server (Bob)
  5. Setting Up the Flutter Client (Alice)
  6. Adding a Third Client (Patrick)
  7. Message Encryption and Decryption
  8. Full Code Example
  9. Testing and Debugging
  10. Conclusion

1. Overview

This implementation facilitates secure and encrypted communication between:

  • Alice: The Flutter client app sending encrypted messages.
  • Bob: The server app receiving, processing, and optionally responding to encrypted messages.
  • Patrick: An optional third client that can join and communicate securely with Alice and Bob.

Key Features

  • Socket Communication: Persistent connection for real-time data exchange.
  • WebSocket Communication: Lightweight and suitable for real-time web and mobile apps.
  • Message Encryption: All messages are encrypted for security.
  • Extensible Design: Additional clients like Patrick can easily be added.

2. Requirements

Tools and Frameworks

  • Flutter: For building the client app.
  • Dart: Programming language for Flutter.
  • Python/Node.js: For building the server app (Bob).
  • WebSocket Protocol: For efficient and real-time messaging.

Dependencies

Flutter

  • web_socket_channel: For WebSocket communication.
  • encrypt: For encryption and decryption.

Server (Bob)

  • Python: websockets or Node.js: ws for WebSocket communication.
  • Cryptography library (PyCrypto, cryptography, or equivalent for encryption).

3. Architecture

Communication Flow

  1. Alice to Bob: Alice encrypts the message and sends it to Bob via a WebSocket.
  2. Bob's Response: Bob decrypts the message, processes it, and sends back an encrypted response.
  3. Patrick Integration: Patrick can establish a WebSocket connection to Bob and Alice for secure communication.

Encryption

  • Algorithm: AES (Advanced Encryption Standard) with a shared secret key.
  • Key Exchange: Use a pre-shared key or implement a Diffie-Hellman key exchange.

4. Setting Up the Server (Bob)

Example Server (Python with WebSockets)

import asyncio
import websockets
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
import os

SECRET_KEY = b"thisisaverysecret!"  # 16 bytes key for AES encryption
IV = b"thisisaninitvect!"  # Initialization vector (16 bytes)

def encrypt_message(message):
    cipher = Cipher(algorithms.AES(SECRET_KEY), modes.CFB(IV))
    encryptor = cipher.encryptor()
    return encryptor.update(message.encode()) + encryptor.finalize()

def decrypt_message(encrypted_message):
    cipher = Cipher(algorithms.AES(SECRET_KEY), modes.CFB(IV))
    decryptor = cipher.decryptor()
    return decryptor.update(encrypted_message) + decryptor.finalize()

async def handle_connection(websocket):
    async for encrypted_message in websocket:
        decrypted_message = decrypt_message(bytes.fromhex(encrypted_message)).decode()
        print(f"Received: {decrypted_message}")

        response = f"Hello, {decrypted_message}!"
        encrypted_response = encrypt_message(response).hex()
        await websocket.send(encrypted_response)

async def main():
    async with websockets.serve(handle_connection, "localhost", 8765):
        print("Server started at ws://localhost:8765")
        await asyncio.Future()  # Run forever

asyncio.run(main())

5. Setting Up the Flutter Client (Alice)

Adding Dependencies

Add the following to pubspec.yaml:

dependencies:
  web_socket_channel: ^2.1.0
  encrypt: ^5.0.0

Client Implementation

import 'dart:convert';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:encrypt/encrypt.dart' as encrypt;

class SecureClient {
  final _channel = WebSocketChannel.connect(Uri.parse('ws://localhost:8765'));

  final key = encrypt.Key.fromUtf8('thisisaverysecret!');
  final iv = encrypt.IV.fromUtf8('thisisaninitvect!');
  final encrypter = encrypt.Encrypter(encrypt.AES(encrypt.Key.fromUtf8('thisisaverysecret!')));

  void sendEncryptedMessage(String message) {
    final encryptedMessage = encrypter.encrypt(message, iv: iv);
    _channel.sink.add(encryptedMessage.base16);
  }

  void listenForMessages() {
    _channel.stream.listen((data) {
      final decryptedMessage = encrypter.decrypt16(data, iv: iv);
      print('Received: $decryptedMessage');
    });
  }

  void closeConnection() {
    _channel.sink.close();
  }
}

void main() {
  final client = SecureClient();
  client.listenForMessages();
  client.sendEncryptedMessage('Alice');
}

6. Adding a Third Client (Patrick)

Patrick's setup is identical to Alice's but uses its own unique connection logic. Patrick communicates securely with Bob and Alice by following the same encryption and WebSocket protocols.


7. Message Encryption and Decryption

Encryption Workflow

  1. Encrypt the message using AES encryption.
  2. Send the encrypted message via WebSocket.

Decryption Workflow

  1. Receive the encrypted message from WebSocket.
  2. Decrypt it using the shared secret key.

Ensure both Alice, Bob, and Patrick use the same encryption keys and initialization vector.


8. Full Code Example

The full code for Alice, Bob, and Patrick can be combined into a repository. Ensure consistent encryption and WebSocket protocols.


9. Testing and Debugging

  1. Run Bob (Server):

    python server.py
  2. Run Alice and Patrick (Flutter Apps):
    Start Alice and Patrick in separate Flutter instances and establish connections.

  3. Test Message Flow:

    • Send messages from Alice to Bob.
    • Verify Bob’s responses.
    • Add Patrick and validate three-way communication.
  4. Debugging Tips:

    • Log encrypted and decrypted messages.
    • Ensure key and IV consistency.

10. Conclusion

This guide demonstrates secure messaging using sockets and WebSockets, supporting multiple clients (Alice, Bob, and Patrick). It ensures encrypted communication using AES, making it suitable for sensitive data transmission.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions