![visualização zk-call [c ++]](https://images.downcodes.com/uploads/20250315/img_67d5683eb87ef30.png)
Esse repositório hospeda uma implementação refinada do protocolo de Schnorr , incorporando inovadoramente uma semente de estado para medidas de segurança aprimoradas. Embora as provas subjacentes possam parecer intrincadas, pretendo elucidar sua funcionalidade da melhor maneira possível. No entanto, para um entendimento mais profundo, incentivo a referência dos trabalhos de pesquisa seminal subjacentes a essa implementação, pois eles oferecem insights abrangentes.

Para uma exploração adicional:
Elíptico baseado em "sabor zero" provas e sua aplicabilidade em dispositivos restritos de recursos por ioannis chatzigiannakis, apostolos pyrgelis, Paul G. Spirakis e Yannis C. Stamatiou

Além disso, esse repositório investiga os conceitos de "Zero-Knowledge" Proofs (ZKPS) e códigos de autenticação de mensagens baseados em hash (HMACs) . Os ZKPs são protocolos criptográficos que permitem que uma parte (o provador) prove a outra parte (o verificador) que uma determinada declaração é verdadeira, sem revelar nenhuma informação adicional além da validade da própria afirmação. Esta propriedade é particularmente valiosa para preservar a privacidade enquanto estabelece confiança.
Por outro lado, os HMACs são um tipo de função de hash criptográfica usada para autenticação de mensagem. Eles envolvem uma função de hash criptográfica (como SHA-256) e uma chave criptográfica secreta. Os HMACs fornecem uma maneira de verificar a integridade dos dados e a autenticidade de uma mensagem, garantindo que ela não tenha sido alterada ou adulterada durante a transmissão e que realmente se origina do pretendente.
No cenário de TI e desenvolvimento de aplicativos de hoje, o cenário de desenvolvimento de aplicativos, as provas de "Zero-Knowledge" emergem como um paradigma fundamental para segurança de autenticação. Sua capacidade de afirmar a validade de uma reivindicação, como provar posse de uma senha secreta - sem revelar nenhuma informação confidencial sobre a própria reivindicação, como senhas ou hashes, revoluciona a garantia de operações seguras de AAA ( autenticação , autorização e contabilidade ).

O ZK-Call & Labs representa uma implementação de um protocolo de Prova (NIZKP) não interativo "Zero-Knowledge", adaptado especificamente para validar segredos baseados em texto. Essa estrutura se mostra inestimável para proteger senhas e outros mecanismos de autenticação, garantindo medidas de segurança robustas sem comprometer a privacidade. Além disso, a integração do HMAC (código de autenticação de mensagens baseado em hash) fortalece ainda mais o processo de autenticação, aprimorando a integridade dos dados e impedindo possíveis violações de segurança.
O protocolo de autenticação empregado nesse sistema opera com base em dois conceitos fundamentais: Proofs (ZKPS) e Código de Autenticação de Mensagens (HMAC) baseado em Hash ( Zero-Knowledge). Vamos nos aprofundar em cada um desses componentes e entender como eles sinergizam para garantir a autenticação segura nos aplicativos de mensagens.
Os ZKPs formam a base de mecanismos de autenticação que preserva a privacidade. Essas provas permitem que uma parte (o provador) demonstre a validade de uma reivindicação a outra parte (o verificador) sem revelar nenhuma informação adicional além da validade da reivindicação. Em essência, os ZKPs permitem a autenticação sem a necessidade de o provador divulgar dados confidenciais, como senhas ou chaves criptográficas.




No contexto dos aplicativos de mensagens, os ZKPs desempenham um papel fundamental na verificação da identidade de um usuário sem a necessidade de transmitir credenciais explícitas pela rede. Em vez disso, os usuários podem gerar provas criptográficas atestando sua identidade ou posse de certas credenciais sem expor essas próprias credenciais. Isso garante que informações sensíveis permaneçam confidenciais durante o processo de autenticação, reforçando a segurança e a privacidade.
O HMAC fornece um mecanismo robusto para verificar a integridade e a autenticidade das mensagens trocadas entre as partes. Envolve o uso de uma função de hash criptográfica em conjunto com uma chave secreta para gerar um código exclusivo (o HMAC) para cada mensagem. Este código serve como uma assinatura digital, permitindo que o destinatário verifique se a mensagem não foi adulterada ou alterada durante a transmissão.

Nos aplicativos de mensagens, o HMAC pode ser empregado para autenticar remetentes de mensagens e garantir a integridade dos canais de comunicação. Ao anexar um HMAC a cada mensagem usando uma chave secreta compartilhada, o remetente e o destinatário podem validar a autenticidade da mensagem após o recebimento. Quaisquer modificações não autorizadas na mensagem resultariam em uma incompatibilidade entre o HMAC calculado e o HMAC recebido , alertando assim o destinatário para potencial adulteração.
Quando combinados, as provas "zero conhecimento" e o HMAC criam uma estrutura formidável para autenticação segura em aplicativos de mensagens. Os ZKPs facilitam a verificação da identidade sem divulgar informações sensíveis, enquanto o HMAC garante a integridade e a autenticidade das mensagens trocadas entre as partes. Juntos, esses mecanismos sustentam a confidencialidade, integridade e autenticidade dos canais de comunicação, protegendo a privacidade e a segurança dos usuários no domínio digital.

A API "HMAC_Client" с+ deve ser simples e intuitiva:
Os Core Components simplificam a criptografia e descriptografia de mensagens seguras, suportando o processamento de nível e nível de caractere para melhorar a proteção de dados.

Método para criptografar uma mensagem processando -a em pedaços .
std::string encrypt_message_by_chunks(const std::string& message);
message: string # The message to be encrypted, processed in chunks
Método para criptografar uma mensagem de um chars .
std::string encrypt_message(const std::string& message);
message: string # The message to be encrypted, processed in characters
Método para descriptografar uma mensagem processando -a em pedaços .
std::string decrypt_message_by_chunks(const std::string& message);
message: string # The message to be decrypted, processed in chunks
Método para descriptografar uma mensagem processando -a em chars .
std::string encrypt_message(const std::string& message);
message: string # The message to be decrypted, processed in characters
TODO: Inclua 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
}