Este Trabajo de Fin de Grado se centra en el diseño e implementación de un sistema de comunicación seguro y eficiente entre dispositivos IoT, utilizando el protocolo D2OTP, que fue desarrollado específicamente para este proyecto. Su objetivo principal es demostrar que se puede crear una infraestructura de transmisión de datos que sea segura, robusta y ligera, ideal para entornos con recursos computacionales limitados y sin depender de conexiones externas a la nube. La propuesta combina microcontroladores asequibles con software libre, algoritmos criptográficos optimizados y una arquitectura distribuida que separa las funciones de los dispositivos, el servidor central y el gestor de claves. En la práctica, se ha creado una red de sensores utilizando placas ESP32-C3 equipadas con sensores DHT22, que están conectadas a una red local a través de Wi-Fi. Cada dispositivo puede medir la temperatura y la humedad del ambiente, cifrar esos datos con una clave de un solo uso mediante el protocolo D2OTP, y enviarlos al servidor usando UDP. Además, el sistema incluye una comunicación bidireccional segura que permite confirmar la recepción de los datos, lo que aumenta la fiabilidad de la transmisión. Esta infraestructura también cuenta con un gestor de claves autónomo, encargado de generar, almacenar y distribuir las claves necesarias para cada uno de los componentes del sistema. El diseño del protocolo D2OTP se basa en el principio del One-Time Pad (OTP) sincronizado mediante contadores, de modo que cada mensaje enviado utiliza una versión de la clave compartida. Para ello, se han creado mecanismos específicos para registrar nuevos dispositivos, actualizar claves, verificar la integridad mediante etiquetas criptográficas (TAGs) y establecer estrategias de recuperación ante desconexiones. Este enfoque ofrece un alto nivel de seguridad sin comprometer la eficiencia, especialmente en comparación con soluciones más pesadas como TLS, que son difíciles de implementar en dispositivos. La implementación se ha realizado completamente en C++ (tanto el firmware como la librería criptográfica), Python (para el backend del servidor y la gestión de claves) y HTML/JavaScript (para la web de visualización en tiempo real). Este sistema es modular, escalable y fácil de replicar, y todos sus componentes han sido creados desde cero, sin depender de plataformas externas. Se ha puesto un énfasis especial en la eficiencia computacional, el consumo de memoria y la facilidad de depuración. La librería D2OTP, que se integra con mbedTLS, permite llevar a cabo operaciones de cifrado y descifrado de manera completamente autónoma en el dispositivo, incluso sin conexión a Internet. Durante las pruebas, se verificaron todas las funcionalidades del sistema a través de simulaciones de escenarios reales: registro de nuevos dispositivos, envío periódico de mediciones, recepción de confirmaciones y validación del cifrado. También se evaluaron métricas clave como la latencia, el uso de recursos en el ESP32 y la respuesta del sistema en condiciones adversas. Los resultados muestran que el sistema opera de manera estable, segura y con una notable eficiencia. Este proyecto presenta varias contribuciones importantes: una arquitectura de red IoT segura y práctica que no depende de recursos externos, un protocolo OTP diseñado específicamente para dispositivos embebidos, y una solución integral que funciona a la perfección en entornos educativos, industriales o domésticos. Todo esto se ha desarrollado con un fuerte enfoque en el software libre, la economía y la sostenibilidad técnica del sistema. Finalmente, se han identificado varias líneas de trabajo futuras que podrían ayudar a escalar el sistema, como la adición de diferentes tipos de sensores. Así que, este TFG no solo cumple con los objetivos que se plantearon al principio, sino que también sienta las bases para el desarrollo de sistemas IoT que sean seguros y accesibles.
ABSTRACT
This Final Degree Project focuses on the design and implementation of a secure and efficient communication system between IoT devices, using the D2OTP protocol, which was developed specifically for this project. Its main objective is to demonstrate that it is possible to create a data transmission infrastructure that is secure, robust and lightweight, ideal for environments with limited computational resources and without relying on external connections to the cloud. The proposal combines affordable microcontrollers with free software, optimised cryptographic algorithms and a distributed architecture that separates the functions of the devices, the central server and the key manager. In practice, a network of sensors has been created using ESP32-C3 boards equipped with DHT22 sensors, which are connected to a local network via WiFi. Each device can measure the temperature and humidity of the environment, encrypt that data with a one-time key using the D2OTP protocol, and send it to the server using UDP. In addition, the system includes secure two-way communication that allows confirmation of data reception, increasing the reliability of transmission. This infrastructure also has an autonomous key manager, responsible for generating, storing and distributing the keys required for each of the system components. The design of the D2OTP protocol is based on the principle of the One-Time Pad (OTP) synchronised by counters, so that each message sent uses a version of the shared key. To this end, specific mechanisms have been created to register new devices, update keys, verify integrity using cryptographic tags (MACs) and establish recovery strategies in the event of disconnections. This approach offers a high level of security without compromising efficiency, especially when compared to heavier solutions such as TLS, which are difficult to implement on devices. The implementation has been done entirely in C++ (both the firmware and the cryptographic library), Python (for the server backend and key management), and HTML/JavaScript (for the real-time visualisation web). This system is modular, scalable, and easy to replicate, and all its components have been created from scratch, without relying on external platforms. Special emphasis has been placed on computational efficiency, memory consumption and ease of debugging. The D2OTP library, which integrates with mbedTLS, allows encryption and decryption operations to be carried out completely autonomously on the device, even without an Internet connection. During testing, all system functionalities were verified through simulations of real-world scenarios: registration of new devices, periodic sending of measurements, reception of confirmations, and encryption validation. Key metrics such as latency, resource usage on the ESP32, and system response under adverse conditions were also evaluated. The results show that the system operates stably, securely, and with remarkable efficiency. This project makes several important contributions: a secure and practical IoT network architecture that does not depend on external resources, an OTP protocol designed specifically for embedded devices, and a comprehensive solution that works seamlessly in educational, industrial, or domestic environments. All of this has been developed with a strong focus on free software, economy, and the technical sustainability of the system. Finally, several future lines of work have been identified that could help scale the system, such as adding different types of sensors. Thus, this TFG not only meets the objectives set out at the beginning, but also lays the foundations for the development of secure and accessible IoT systems.
Este Trabajo de Fin de Grado se centra en el diseño e implementación de un sistema de comunicación seguro y eficiente entre dispositivos IoT, utilizando el protocolo D2OTP, que fue desarrollado específicamente para este proyecto. Su objetivo principal es demostrar que se puede crear una infraestructura de transmisión de datos que sea segura, robusta y ligera, ideal para entornos con recursos computacionales limitados y sin depender de conexiones externas a la nube. La propuesta combina microcontroladores asequibles con software libre, algoritmos criptográficos optimizados y una arquitectura distribuida que separa las funciones de los dispositivos, el servidor central y el gestor de claves. En la práctica, se ha creado una red de sensores utilizando placas ESP32-C3 equipadas con sensores DHT22, que están conectadas a una red local a través de Wi-Fi. Cada dispositivo puede medir la temperatura y la humedad del ambiente, cifrar esos datos con una clave de un solo uso mediante el protocolo D2OTP, y enviarlos al servidor usando UDP. Además, el sistema incluye una comunicación bidireccional segura que permite confirmar la recepción de los datos, lo que aumenta la fiabilidad de la transmisión. Esta infraestructura también cuenta con un gestor de claves autónomo, encargado de generar, almacenar y distribuir las claves necesarias para cada uno de los componentes del sistema. El diseño del protocolo D2OTP se basa en el principio del One-Time Pad (OTP) sincronizado mediante contadores, de modo que cada mensaje enviado utiliza una versión de la clave compartida. Para ello, se han creado mecanismos específicos para registrar nuevos dispositivos, actualizar claves, verificar la integridad mediante etiquetas criptográficas (TAGs) y establecer estrategias de recuperación ante desconexiones. Este enfoque ofrece un alto nivel de seguridad sin comprometer la eficiencia, especialmente en comparación con soluciones más pesadas como TLS, que son difíciles de implementar en dispositivos. La implementación se ha realizado completamente en C++ (tanto el firmware como la librería criptográfica), Python (para el backend del servidor y la gestión de claves) y HTML/JavaScript (para la web de visualización en tiempo real). Este sistema es modular, escalable y fácil de replicar, y todos sus componentes han sido creados desde cero, sin depender de plataformas externas. Se ha puesto un énfasis especial en la eficiencia computacional, el consumo de memoria y la facilidad de depuración. La librería D2OTP, que se integra con mbedTLS, permite llevar a cabo operaciones de cifrado y descifrado de manera completamente autónoma en el dispositivo, incluso sin conexión a Internet. Durante las pruebas, se verificaron todas las funcionalidades del sistema a través de simulaciones de escenarios reales: registro de nuevos dispositivos, envío periódico de mediciones, recepción de confirmaciones y validación del cifrado. También se evaluaron métricas clave como la latencia, el uso de recursos en el ESP32 y la respuesta del sistema en condiciones adversas. Los resultados muestran que el sistema opera de manera estable, segura y con una notable eficiencia. Este proyecto presenta varias contribuciones importantes: una arquitectura de red IoT segura y práctica que no depende de recursos externos, un protocolo OTP diseñado específicamente para dispositivos embebidos, y una solución integral que funciona a la perfección en entornos educativos, industriales o domésticos. Todo esto se ha desarrollado con un fuerte enfoque en el software libre, la economía y la sostenibilidad técnica del sistema. Finalmente, se han identificado varias líneas de trabajo futuras que podrían ayudar a escalar el sistema, como la adición de diferentes tipos de sensores. Así que, este TFG no solo cumple con los objetivos que se plantearon al principio, sino que también sienta las bases para el desarrollo de sistemas IoT que sean seguros y accesibles.
ABSTRACT
This Final Degree Project focuses on the design and implementation of a secure and efficient communication system between IoT devices, using the D2OTP protocol, which was developed specifically for this project. Its main objective is to demonstrate that it is possible to create a data transmission infrastructure that is secure, robust and lightweight, ideal for environments with limited computational resources and without relying on external connections to the cloud. The proposal combines affordable microcontrollers with free software, optimised cryptographic algorithms and a distributed architecture that separates the functions of the devices, the central server and the key manager. In practice, a network of sensors has been created using ESP32-C3 boards equipped with DHT22 sensors, which are connected to a local network via WiFi. Each device can measure the temperature and humidity of the environment, encrypt that data with a one-time key using the D2OTP protocol, and send it to the server using UDP. In addition, the system includes secure two-way communication that allows confirmation of data reception, increasing the reliability of transmission. This infrastructure also has an autonomous key manager, responsible for generating, storing and distributing the keys required for each of the system components. The design of the D2OTP protocol is based on the principle of the One-Time Pad (OTP) synchronised by counters, so that each message sent uses a version of the shared key. To this end, specific mechanisms have been created to register new devices, update keys, verify integrity using cryptographic tags (MACs) and establish recovery strategies in the event of disconnections. This approach offers a high level of security without compromising efficiency, especially when compared to heavier solutions such as TLS, which are difficult to implement on devices. The implementation has been done entirely in C++ (both the firmware and the cryptographic library), Python (for the server backend and key management), and HTML/JavaScript (for the real-time visualisation web). This system is modular, scalable, and easy to replicate, and all its components have been created from scratch, without relying on external platforms. Special emphasis has been placed on computational efficiency, memory consumption and ease of debugging. The D2OTP library, which integrates with mbedTLS, allows encryption and decryption operations to be carried out completely autonomously on the device, even without an Internet connection. During testing, all system functionalities were verified through simulations of real-world scenarios: registration of new devices, periodic sending of measurements, reception of confirmations, and encryption validation. Key metrics such as latency, resource usage on the ESP32, and system response under adverse conditions were also evaluated. The results show that the system operates stably, securely, and with remarkable efficiency. This project makes several important contributions: a secure and practical IoT network architecture that does not depend on external resources, an OTP protocol designed specifically for embedded devices, and a comprehensive solution that works seamlessly in educational, industrial, or domestic environments. All of this has been developed with a strong focus on free software, economy, and the technical sustainability of the system. Finally, several future lines of work have been identified that could help scale the system, such as adding different types of sensors. Thus, this TFG not only meets the objectives set out at the beginning, but also lays the foundations for the development of secure and accessible IoT systems. Read More


