![Vista previa de ZK-Call [C ++]](https://images.downcodes.com/uploads/20250315/img_67d5683eb87ef30.png)
Este repositorio alberga una implementación refinada del protocolo de Schnorr , incorporando innovadoras una semilla de estado para medidas de seguridad mejoradas. Si bien las pruebas subyacentes pueden parecer intrincadas, mi objetivo es dilucidar su funcionalidad lo mejor que pueda. Sin embargo, para una comprensión más profunda, aliento a hacer referencia a los documentos de investigación seminales que sustentan esta implementación, ya que ofrecen información integral.

Para una mayor exploración:
Pruebas de "conocimiento cero" basado en la curva elíptica y su aplicabilidad en dispositivos restringidos de recursos por Ioannis Chatzigiannakis, Apostolos Pyrgelis, Paul G. Spirakis y Yannis C. Stamatiou

Además, este repositorio profundiza en los conceptos de pruebas de "conocimiento cero" (ZKPS) y códigos de autenticación de mensajes basados en el hash (HMACS) . Los ZKP son protocolos criptográficos que permiten a una parte (la Prover) demostrarle a otra parte (el verificador) que una declaración dada es verdadera, sin revelar ninguna información adicional más allá de la validez de la declaración misma. Esta propiedad es particularmente valiosa para preservar la privacidad al establecer la confianza.
Por otro lado, los HMAC son un tipo de función hash criptográfica utilizada para la autenticación de mensajes. Implican una función hash criptográfica (como SHA-256) y una clave criptográfica secreta. Los HMAC proporcionan una forma de verificar tanto la integridad de los datos como la autenticidad de un mensaje, asegurando que no haya sido alterado o alterado durante la transmisión y que de hecho se origina en el supuesto remitente.
En el panorama de desarrollo de TI y aplicaciones que evolucionan rápidamente en la actualidad, las pruebas de "conocimiento cero" (ZKP) emergen como un paradigma fundamental para la seguridad de la autenticación. Su capacidad para afirmar la validez de un reclamo, como probar la posesión de una contraseña secreta, sin revelar ninguna información confidencial sobre el reclamo en sí, como contraseñas o hashes, revoluciona la garantía de operaciones seguras de AAA ( autenticación , autorización y contabilidad ).

ZK-Call & Labs representa una implementación de un protocolo de prueba de "conocimiento cero" no interactivo (NIZKP) adaptado específicamente para validar secretos basados en texto. Este marco resulta invaluable para salvaguardar las contraseñas y otros mecanismos de autenticación, asegurando medidas de seguridad sólidas sin comprometer la privacidad. Además, la integración de HMAC (código de autenticación de mensajes basado en HASH) fortalece aún más el proceso de autenticación, mejorando la integridad de los datos y frustrando las posibles infracciones de seguridad.
El protocolo de autenticación empleado en este sistema opera en función de dos conceptos fundamentales: pruebas de "conocimiento cero" (ZKPS) y código de autenticación de mensajes basado en el hash (HMAC) . Vamos a profundizar en cada uno de estos componentes y comprender cómo se sinergen para garantizar la autenticación segura en las aplicaciones de mensajería.
Los ZKP forman la base de los mecanismos de autenticación de preservación de la privacidad. Estas pruebas permiten que una parte (el Prover) demuestre la validez de un reclamo a otra parte (el verificador) sin revelar ninguna información adicional más allá de la validez del reclamo. En esencia, los ZKP habilitan la autenticación sin la necesidad de que el Prover revele datos confidenciales, como contraseñas o claves criptográficas.




En el contexto de las aplicaciones de mensajería, los ZKP juegan un papel fundamental en la verificación de la identidad de un usuario sin la necesidad de transmitir credenciales explícitas a través de la red. En cambio, los usuarios pueden generar pruebas criptográficas que atestiguan su identidad o posesión de ciertas credenciales sin exponer esas credenciales ellos mismos. Esto garantiza que la información confidencial permanezca confidencial durante el proceso de autenticación, reforzando la seguridad y la privacidad.
HMAC proporciona un mecanismo robusto para verificar la integridad y la autenticidad de los mensajes intercambiados entre las partes. Implica el uso de una función hash criptográfica junto con una clave secreta para generar un código único (el HMAC) para cada mensaje. Este código sirve como una firma digital, lo que permite que el destinatario verifique que el mensaje no haya sido alterado o alterado durante la transmisión.

En las aplicaciones de mensajería, HMAC se puede emplear para autenticar los remitentes de mensajes y garantizar la integridad de los canales de comunicación. Al agregar un HMAC a cada mensaje utilizando una clave secreta compartida, tanto el remitente como el destinatario pueden validar la autenticidad del mensaje al recibir. Cualquier modificación no autorizada al mensaje daría como resultado un desajuste entre el HMAC calculado y el HMAC recibido , alertando así al destinatario sobre la posible manipulación.
Cuando se combinan, las pruebas de "conocimiento cero" y HMAC crean un marco formidable para la autenticación segura en aplicaciones de mensajería. Los ZKP facilitan la verificación de identidad sin divulgar información confidencial, mientras que HMAC garantiza la integridad y la autenticidad de los mensajes intercambiados entre las partes. Juntos, estos mecanismos mantienen la confidencialidad, la integridad y la autenticidad de los canales de comunicación, salvaguardando la privacidad y la seguridad de los usuarios en el ámbito digital.

La API "HMAC_Client" с ++ está destinada a ser simple e intuitiva:
Los Core Components agilizan el cifrado y el descifrado de mensajes seguros, lo que respalda tanto el procesamiento de fragmentos como a nivel de caracteres para una mejor protección de datos.

Método para cifrar un mensaje procesándolo en fragmentos .
std::string encrypt_message_by_chunks(const std::string& message);
message: string # The message to be encrypted, processed in chunks
Método para cifrar un mensaje por un chars .
std::string encrypt_message(const std::string& message);
message: string # The message to be encrypted, processed in characters
Método para descifrar un mensaje procesándolo en fragmentos .
std::string decrypt_message_by_chunks(const std::string& message);
message: string # The message to be decrypted, processed in chunks
Método para descifrar un mensaje procesándolo en caracteres .
std::string encrypt_message(const std::string& message);
message: string # The message to be decrypted, processed in characters
TODO: incluye Example Usage
#include <iostream> // Include the input/output stream standard header
#include <thread> // Include the thread standard header
#include <queue> // Include the queue standard header
#include <string> // Include the string standard header
#include "src/HMAC/core/base.h" // Include the header file for HMAC_Client functionality
#include "src/SeedGeneration/core/base.h" // Include the header file for SeedGenerator functionality
constexpr bool DEBUG = true; // Define a constexpr boolean variable DEBUG with value true
void print_msg(const std::string &who, const std::string &message) { // Define a function to print messages
if (DEBUG) { // Check if debugging is enabled
std::cout << "[" << who << "] " << message << std::endl; // Print the message with source identifier
}
}
bool check_if_queue_empty(std::queue<std::string> &socket) { // Define a function to check if a queue is empty
while (true) { // Infinite loop
if (!socket.empty()) { // Check if the queue is not empty
return true; // Return true if the queue is not empty
}
}
}
std::string get_content_from_socket(std::queue<std::string> &socket) { // Define a function to get content from a socket (queue)
if (check_if_queue_empty(socket)) { // Check if the queue is not empty
std::string val = socket.front(); // Get the front element of the queue
socket.pop(); // Remove the front element from the queue
return val; // Return the retrieved value
}
}
void client(std::queue<std::string> &client_socket, std::queue<std::string> &server_socket) { // Define the client function
// Generating the main seed
SeedGenerator seed_generator("job"); // Create an instance of SeedGenerator
std::vector<unsigned char> main_seed = seed_generator.generate(); // Generate the main seed
// Creating an instance of HMAC_Client for encrypting messages
print_msg("client", "first");
HMAC_Client obj("sha256", main_seed, 1); // Create an instance of HMAC_Client
// Sending the main seed to the server
server_socket.emplace(main_seed.begin(), main_seed.end()); // Convert the main seed vector to a string and send it to the server
print_msg("client", "after obj");
// Checking if the server has successfully received the seed
if (get_content_from_socket(client_socket) == obj.encrypt_message("")) { // Check if the server received the seed
print_msg("client", "after if");
// If successful, send a message to the server
std::string message = "hello"; // Define the message to be sent
server_socket.push(obj.encrypt_message_by_chunks(message)); // Encrypt and send the message to the server
print_msg("client", "client sent message " + message);
// Checking if the server has successfully decrypted the message
if (get_content_from_socket(client_socket) == obj.encrypt_message(message)) { // Check if the server decrypted the message
print_msg("client", "server has decrypted message");
}
}
}
void server(std::queue<std::string> &server_socket, std::queue<std::string> &client_socket) { // Define the server function
// Receiving the main seed from the client
std::string main_seed = get_content_from_socket(server_socket); // Receive the main seed from the client
// Creating an instance of HMAC_Client for encrypting messages
HMAC_Client obj("sha256", std::vector<unsigned char>(main_seed.begin(), main_seed.end()), 1); // Create an instance of HMAC_Client
// Sending an empty message to the client as acknowledgment
client_socket.push(obj.encrypt_message("")); // Encrypt and send an empty message to the client as acknowledgment
// Receiving the encrypted message from the client
std::string msg = get_content_from_socket(server_socket); // Receive the encrypted message from the client
print_msg("server", "message encrypted: " + msg);
// Decrypting the message
print_msg("server", "before decrypt ");
std::string msg_raw = obj.decrypt_message_by_chunks(msg); // Decrypt the received message
print_msg("server", "message raw: " + msg_raw);
// Sending the encrypted message back to the client
client_socket.push(obj.encrypt_message(msg_raw)); // Encrypt and send the decrypted message back to the client
}
int main() { // Main function
std::queue<std::string> client_socket, server_socket; // Create queues for client and server sockets
std::thread client_thread(client, std::ref(client_socket), std::ref(server_socket)); // Create a thread for the client function
std::thread server_thread(server, std::ref(server_socket), std::ref(client_socket)); // Create a thread for the server function
// Joining the threads to wait for their completion
client_thread.join(); // Wait for the client thread to finish
server_thread.join(); // Wait for the server thread to finish
return 0; // Return 0 to indicate successful execution
}
#include "src/ZeroKnowledge/core/base.h" // Include the header file for ZeroKnowledge class
int main() { // Main function
// Creating a ZeroKnowledge object for the client with specified curve and hash algorithm
ZeroKnowledge clientObject = ZeroKnowledge::createNew("secp256k1", "sha3_256");
// Creating a ZeroKnowledge object for the server with specified curve and hash algorithm
ZeroKnowledge serverObject = ZeroKnowledge::createNew("secp384r1", "sha3_512");
// Setting the server password
std::string serverPassword = "SecretServerPassword";
// Creating a signature for the server password
ZeroKnowledgeSignature serverSignature = serverObject.createSignature(serverPassword);
// Creating a signature for the client identity
std::string identity = "John";
ZeroKnowledgeSignature clientSignature = clientObject.createSignature(identity);
std::cout<<"beforen";
// Generating a token signed by the server for the client
std::cout<<clientObject.token()<<"n";
ZeroKnowledgeData token = serverObject.sign(serverPassword, clientObject.token());
std::cout<<"aftern";
// Generating proof using client identity and token
ZeroKnowledgeData proof = clientObject.sign(identity, token.data);
// Verifying the received proof
bool serverVerification = serverObject.verify(token, serverSignature);
if (!serverVerification) { // Check if server verification failed
std::cout << "Server verification failed" << std::endl; // Print error message
} else { // If server verification succeeded
// Otherwise, verify the proof using client signature
bool clientVerification = clientObject.verify(token, clientSignature, proof.proof);
if (!clientVerification) { // Check if client verification failed
std::cout << "Client verification failed" << std::endl; // Print error message
} else { // If client verification succeeded
std::cout << "Authentication successful" << std::endl; // Print success message
}
}
return 0; // Return 0 to indicate successful execution
}
#include "src/ZeroKnowledge/core/base.h" // Include the header file for ZeroKnowledge class
#include "src/HMAC/core/base.h" // Include the header file for HMAC_Client functionality
#include "src/SeedGeneration/core/base.h" // Include the header file for SeedGenerator functionality
#include <iostream> // Include the input/output stream standard header
#include <thread> // Include the thread standard header
#include <queue> // Include the queue standard header
#include <string> // Include the string standard header
constexpr bool DEBUG = true; // Define a constexpr boolean variable DEBUG with value true
void print_msg(const std::string &who, const std::string &message) { // Define a function to print messages
if (DEBUG) { // Check if debugging is enabled
std::cout << "[" << who << "] " << message << std::endl; // Print the message with source identifier
}
}
bool check_if_queue_empty(std::queue<std::string> &socket) { // Define a function to check if a queue is empty
while (true) { // Infinite loop
if (!socket.empty()) { // Check if the queue is not empty
return true; // Return true if the queue is not empty
}
}
}
std::string get_content_from_socket(std::queue<std::string> &socket) { // Define a function to get content from a socket (queue)
if (check_if_queue_empty(socket)) { // Check if the queue is not empty
std::string val = socket.front(); // Get the front element of the queue
socket.pop(); // Remove the front element from the queue
return val; // Return the retrieved value
}
}
void client(std::queue<std::string> &client_socket, std::queue<std::string> &server_socket) { // Define the client function
// Generating the main seed
SeedGenerator seed_generator("job"); // Create an instance of SeedGenerator
std::vector<unsigned char> main_seed = seed_generator.generate(); // Generate the main seed
// Creating an instance of HMAC_Client for encrypting messages
print_msg("client", "first");
HMAC_Client obj("sha256", main_seed, 1); // Create an instance of HMAC_Client
// Sending the main seed to the server
server_socket.emplace(main_seed.begin(), main_seed.end()); // Convert the main seed vector to a string and send it to the server
print_msg("client", "after obj");
// Checking if the server has successfully received the seed
if (get_content_from_socket(client_socket) == obj.encrypt_message("")) { // Check if the server received the seed
print_msg("client", "after if");
// If successful, send a message to the server
std::string message = "hello"; // Define the message to be sent
server_socket.push(obj.encrypt_message_by_chunks(message)); // Encrypt and send the message to the server
print_msg("client", "client sent message " + message);
// Checking if the server has successfully decrypted the message
if (get_content_from_socket(client_socket) == obj.encrypt_message(message)) { // Check if the server decrypted the message
print_msg("client", "server has decrypted message");
}
}
}
void server(std::queue<std::string> &server_socket, std::queue<std::string> &client_socket) { // Define the server function
// Receiving the main seed from the client
std::string main_seed = get_content_from_socket(server_socket); // Receive the main seed from the client
// Creating an instance of HMAC_Client for encrypting messages
HMAC_Client obj("sha256", std::vector<unsigned char>(main_seed.begin(), main_seed.end()), 1); // Create an instance of HMAC_Client
// Sending an empty message to the client as acknowledgment
client_socket.push(obj.encrypt_message("")); // Encrypt and send an empty message to the client as acknowledgment
// Receiving the encrypted message from the client
std::string msg = get_content_from_socket(server_socket); // Receive the encrypted message from the client
print_msg("server", "message encrypted: " + msg);
// Decrypting the message
print_msg("server", "before decrypt ");
std::string msg_raw = obj.decrypt_message_by_chunks(msg); // Decrypt the received message
print_msg("server", "message raw: " + msg_raw);
// Sending the encrypted message back to the client
client_socket.push(obj.encrypt_message(msg_raw)); // Encrypt and send the decrypted message back to the client
}
void init_talking() { // Define a function to initialize client-server communication
std::queue<std::string> client_socket, server_socket; // Create queues for client and server sockets
std::thread client_thread(client, std::ref(client_socket), std::ref(server_socket)); // Create a thread for the client function
std::thread server_thread(server, std::ref(server_socket), std::ref(client_socket)); // Create a thread for the server function
// Joining the threads to wait for their completion
client_thread.join(); // Wait for the client thread to finish
server_thread.join(); // Wait for the server thread to finish
}
int main() { // Main function
// Creating a ZeroKnowledge object for the client with specified curve and hash algorithm
ZeroKnowledge clientObject = ZeroKnowledge::createNew("secp256k1", "sha3_256");
// Creating a ZeroKnowledge object for the server with specified curve and hash algorithm
ZeroKnowledge serverObject = ZeroKnowledge::createNew("secp384r1", "sha3_512");
// Setting the server password
std::string serverPassword = "SecretServerPassword";
// Creating a signature for the server password
ZeroKnowledgeSignature serverSignature = serverObject.createSignature(serverPassword);
// Creating a signature for the client identity
std::string identity = "John";
ZeroKnowledgeSignature clientSignature = clientObject.createSignature(identity);
std::cout << "beforen";
// Generating a token signed by the server for the client
std::cout << clientObject.token() << "n";
ZeroKnowledgeData token = serverObject.sign(serverPassword, clientObject.token());
std::cout << "aftern";
// Generating proof using client identity and token
ZeroKnowledgeData proof = clientObject.sign(identity, token.data);
// Verifying the received proof
bool serverVerification = serverObject.verify(token, serverSignature);
if (!serverVerification) { // Check if server verification failed
std::cout << "Server verification failed" << std::endl; // Print error message
} else { // If server verification succeeded
// Otherwise, verify the proof using client signature
bool clientVerification = clientObject.verify(token, clientSignature, proof.proof);
if (!clientVerification) { // Check if client verification failed
std::cout << "Client verification failed" << std::endl; // Print error message
} else { // If client verification succeeded
std::cout << "Authentication successful" << std::endl; // Print success message
init_talking(); // Initialize client-server communication
}
}
return 0; // Return 0 to indicate successful execution
}