![Предварительный просмотр ZK-Call [C ++]](https://images.downcodes.com/uploads/20250315/img_67d5683eb87ef30.png)
В этом хранилище проводится утонченная реализация протокола Schnorr , инновационно включая в себя семена состояния для расширенных мер безопасности. Хотя основные доказательства могут показаться сложными, я стремлюсь выяснить их функциональность в меру своих возможностей. Тем не менее, для более глубокого понимания я рекомендую ссылаться на основополагающие исследования, лежащие в основе этой реализации, поскольку они предлагают всестороннюю информацию.

Для дальнейшего изучения:
Эллиптические кривые, основанные на «нулевых знаниях», и их применимость к устройствам с ограниченными ресурсами, с которыми сталкивается Иоаннис Чацигианнакис, Апостолос Пиргелис, Пол Г. Спиракис и Яннис С. Стаматиу

Кроме того, этот репозиторий углубляется в концепции доказательств «нулевого знания» (ZKP) и кодов аутентификации сообщений на основе хеш (HMAC) . ZKP - это криптографические протоколы, которые позволяют одной стороне (Prover) доказать другой стороне (проверке), что данное утверждение является истинным, не выявляя какую -либо дополнительную информацию за пределами обоснованности самого утверждения. Эта собственность особенно ценна для сохранения конфиденциальности при установлении доверия.
С другой стороны, HMAC - это тип криптографической хеш -функции, используемой для аутентификации сообщений. Они включают криптографическую хэш-функцию (такую как SHA-256) и секретный криптографический ключ. HMAC обеспечивают способ проверить как целостность данных, так и подлинность сообщения, гарантируя, что оно не было изменено или не подделано во время передачи и что оно действительно происходит от предполагаемого отправителя.
В сегодняшней быстро развивающейся ландшафте разработки приложений и ландшафта разработки приложений «доказательства нулевого знания» (ZKP) становятся ключевой парадигмой для безопасности аутентификации. Их способность подтвердить обоснованность претензии, такую как доказательство владения секретным паролем - без раскрытия какой -либо конфиденциальной информации о самой претензии, такой как пароли или хэши, революционизирует гарантирование безопасных операций AAA ( аутентификация , разрешение и бухгалтерский учет ).

ZK-Call & Labs представляет собой реализацию неинтерактивного протокола «нулевого знания» (NIZKP), специально предназначенного для проверки текстовых секретов. Эта структура оказывается бесценной для защиты паролей и других механизмов аутентификации, обеспечивая надежные меры безопасности без ущерба для конфиденциальности. Кроме того, интеграция HMAC (код аутентификации на основе хеш-сообщений) дополнительно укрепляет процесс аутентификации, повышая целостность данных и предотвращая потенциальные нарушения безопасности.
Протокол аутентификации, используемый в этой системе, работает на основе двух фундаментальных концепций: «Доказания нулевого знания» (ZKP) и код аутентификации сообщений на основе хеш (HMAC) . Давайте углубимся в каждый из этих компонентов и поймем, как они синергируют, чтобы обеспечить безопасную аутентификацию в приложениях обмена сообщениями.
ZKP образуют основу из механизмов аутентификации, сохраняющих конфиденциальность. Эти доказательства позволяют одной стороне (Prover) продемонстрировать обоснованность претензии на другую сторону (проверку), не выявляя какую -либо дополнительную информацию, помимо обоснованности претензии. По сути, ZKPS включает аутентификацию без необходимости раскрытия конфиденциальных данных, таких как пароли или криптографические ключи.




В контексте приложений обмена сообщениями ZKP играют ключевую роль в проверке идентификации пользователя без необходимости передачи явных учетных данных по сети. Вместо этого пользователи могут генерировать криптографические доказательства, подтверждающие их личность или владение определенными учетными данными, не разоблачая эти учетные данные сами. Это гарантирует, что конфиденциальная информация остается конфиденциальной в процессе аутентификации, поддерживая безопасность и конфиденциальность.
HMAC обеспечивает надежный механизм для проверки целостности и подлинности сообщений, обменяемых между сторонами. Он включает в себя использование криптографической хэш -функции в сочетании с секретным ключом для создания уникального кода (HMAC) для каждого сообщения. Этот код служит цифровой подписью, позволяя получателю убедиться, что сообщение не было подделано или изменено во время передачи.

В приложениях обмена сообщениями HMAC может быть использован для аутентификации отправителей сообщений и обеспечения целостности каналов связи. Добавив HMAC к каждому сообщению, используя общий секретный ключ, как отправитель, так и получатель могут проверить подлинность сообщения при получении. Любые несанкционированные модификации сообщения приведут к несоответствию между вычисленным HMAC и полученным HMAC , тем самым предупредив получателя о потенциальном подделках.
В комбинированных доказательствах «нулевые знания» и HMAC создают грозную основу для безопасной аутентификации в приложениях обмена сообщениями. ZKP облегчают проверку идентификации без разглашения конфиденциальной информации, в то время как HMAC обеспечивает целостность и подлинность сообщений, обмениваемых между сторонами. Вместе эти механизмы поддерживают конфиденциальность, целостность и подлинность каналов связи, защищая конфиденциальность пользователей и безопасность в цифровой сфере.

API "HMAC_Client" C ++ предназначен для того, чтобы быть простым и интуитивно понятным:
Core Components оптимизируют безопасное шифрование и дешифрование сообщений , поддерживая обработку как чанка , так и на уровне символов для повышения защиты данных.

Метод для шифрования сообщения , обрабатывая его в куски .
std::string encrypt_message_by_chunks(const std::string& message);
message: string # The message to be encrypted, processed in chunks
Метод для шифрования сообщения у Chars .
std::string encrypt_message(const std::string& message);
message: string # The message to be encrypted, processed in characters
Метод для расшифровки сообщения , обрабатывая его в кусках .
std::string decrypt_message_by_chunks(const std::string& message);
message: string # The message to be decrypted, processed in chunks
Метод для расшифровки сообщения , обрабатывая его в Chars .
std::string encrypt_message(const std::string& message);
message: string # The message to be decrypted, processed in characters
TODO: включить 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
}