### Example Usage Source: https://github.com/jedisct1/libsodium-doc/blob/master/public-key_cryptography/key_encapsulation.md A C code example demonstrating the usage of the KEM API. ```APIDOC ## Example Usage ```c #include int main() { // Initialize libsodium if (sodium_init() < 0) { // Handle error return 1; } unsigned char pk[crypto_kem_PUBLICKEYBYTES]; unsigned char sk[crypto_kem_SECRETKEYBYTES]; unsigned char ciphertext[crypto_kem_CIPHERTEXTBYTES]; unsigned char client_key[crypto_kem_SHAREDSECRETBYTES]; unsigned char server_key[crypto_kem_SHAREDSECRETBYTES]; // Generate key pair if (crypto_kem_keypair(pk, sk) != 0) { // Handle error return 1; } // Encapsulate: Sender generates ciphertext and shared secret if (crypto_kem_enc(ciphertext, client_key, pk) != 0) { // Handle error return 1; } // Decapsulate: Recipient uses ciphertext and secret key to get shared secret if (crypto_kem_dec(server_key, ciphertext, sk) != 0) { // Handle error return 1; } // Now client_key and server_key should be identical. // You can use these shared secrets for symmetric encryption or feed them to a KDF. return 0; } ``` ``` -------------------------------- ### Key Exchange Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/scalar_multiplication.md Example demonstrating a secure key exchange using crypto_scalarmult and crypto_generichash. ```APIDOC ## Key Exchange Example ### Description This example demonstrates how to perform a secure key exchange between a client and a server using libsodium's `crypto_scalarmult` and `crypto_generichash` functions. It ensures that both parties derive the same shared secret key. ### Method C functions ### Endpoint N/A ### Parameters None ### Request Example ```c // Client and Server Key Pair Generation unsigned char client_publickey[crypto_box_PUBLICKEYBYTES]; unsigned char client_secretkey[crypto_box_SECRETKEYBYTES]; unsigned char server_publickey[crypto_box_PUBLICKEYBYTES]; unsigned char server_secretkey[crypto_box_SECRETKEYBYTES]; // Initialize keys (example using random bytes) randombytes_buf(client_secretkey, sizeof client_secretkey); crypto_scalarmult_base(client_publickey, client_secretkey); randombytes_buf(server_secretkey, sizeof server_secretkey); crypto_scalarmult_base(server_publickey, server_secretkey); // Client derives shared key unsigned char scalarmult_q_by_client[crypto_scalarmult_BYTES]; unsigned char sharedkey_by_client[crypto_generichash_BYTES]; crypto_generichash_state h_client; if (crypto_scalarmult(scalarmult_q_by_client, client_secretkey, server_publickey) != 0) { /* Error */ } crypto_generichash_init(&h_client, NULL, 0U, sizeof sharedkey_by_client); crypto_generichash_update(&h_client, scalarmult_q_by_client, sizeof scalarmult_q_by_client); crypto_generichash_update(&h_client, client_publickey, sizeof client_publickey); crypto_generichash_update(&h_client, server_publickey, sizeof server_publickey); crypto_generichash_final(&h_client, sharedkey_by_client, sizeof sharedkey_by_client); // Server derives shared key unsigned char scalarmult_q_by_server[crypto_scalarmult_BYTES]; unsigned char sharedkey_by_server[crypto_generichash_BYTES]; crypto_generichash_state h_server; if (crypto_scalarmult(scalarmult_q_by_server, server_secretkey, client_publickey) != 0) { /* Error */ } crypto_generichash_init(&h_server, NULL, 0U, sizeof sharedkey_by_server); crypto_generichash_update(&h_server, scalarmult_q_by_server, sizeof scalarmult_q_by_server); crypto_generichash_update(&h_server, client_publickey, sizeof client_publickey); crypto_generichash_update(&h_server, server_publickey, sizeof server_publickey); crypto_generichash_final(&h_server, sharedkey_by_server, sizeof sharedkey_by_server); // sharedkey_by_client and sharedkey_by_server are identical ``` ### Response #### Success Response Both `sharedkey_by_client` and `sharedkey_by_server` will contain the same derived shared secret key upon successful execution. #### Response Example ```c // sharedkey_by_client and sharedkey_by_server contain the derived shared key. ``` ``` -------------------------------- ### Multi-part SHA3-256 Hashing Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/sha-3_hash_function.md Illustrates how to hash a message in multiple parts using SHA3-256. Initialize the state, update it with message chunks, and finalize to get the hash. The state must be reinitialized if reused. ```c #define MESSAGE_PART1 \ ((const unsigned char *) "Arbitrary data to hash") #define MESSAGE_PART1_LEN 22 #define MESSAGE_PART2 \ ((const unsigned char *) "is longer than expected") #define MESSAGE_PART2_LEN 23 unsigned char out[crypto_hash_sha3256_BYTES]; crypto_hash_sha3256_state state; crypto_hash_sha3256_init(&state); crypto_hash_sha3256_update(&state, MESSAGE_PART1, MESSAGE_PART1_LEN); crypto_hash_sha3256_update(&state, MESSAGE_PART2, MESSAGE_PART2_LEN); crypto_hash_sha3256_final(&state, out); ``` -------------------------------- ### Multi-part HMAC Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/hmac-sha2.md Example demonstrating the multi-part (streaming) HMAC-SHA-512 usage. ```APIDOC ## Multi-part HMAC Example ### Description This example demonstrates how to compute an HMAC-SHA-512 hash for a message that is processed in multiple parts (streaming). ### Code ```c #define MESSAGE_PART1 \ ((const unsigned char *) "Arbitrary data to hash") #define MESSAGE_PART1_LEN 22 #define MESSAGE_PART2 \ ((const unsigned char *) "is longer than expected") #define MESSAGE_PART2_LEN 23 unsigned char hash[crypto_auth_hmacsha512_BYTES]; unsigned char key[crypto_auth_hmacsha512_KEYBYTES]; crypto_auth_hmacsha512_state state; crypto_auth_hmacsha512_keygen(key); crypto_auth_hmacsha512_init(&state, key, sizeof key); crypto_auth_hmacsha512_update(&state, MESSAGE_PART1, MESSAGE_PART1_LEN); crypto_auth_hmacsha512_update(&state, MESSAGE_PART2, MESSAGE_PART2_LEN); crypto_auth_hmacsha512_final(&state, hash); ``` ``` -------------------------------- ### Example: Deterministic IP Encryption Source: https://github.com/jedisct1/libsodium-doc/blob/master/ip_address_encryption/README.md Demonstrates generating a key, parsing an IP, encrypting it deterministically, and then decrypting it back. Requires libsodium initialization. ```c #include #include #include int main(void) { unsigned char key[crypto_ipcrypt_KEYBYTES]; unsigned char addr[crypto_ipcrypt_BYTES]; unsigned char encrypted[crypto_ipcrypt_BYTES]; unsigned char decrypted[crypto_ipcrypt_BYTES]; char ip_str[46]; if (sodium_init() < 0) { return 1; } /* Generate a random key */ crypto_ipcrypt_keygen(key); /* Parse an IP address */ if (sodium_ip2bin(addr, "192.0.2.1", strlen("192.0.2.1")) != 0) { return 1; } /* Encrypt */ crypto_ipcrypt_encrypt(encrypted, addr, key); /* The encrypted address can be displayed as an IP */ sodium_bin2ip(ip_str, sizeof ip_str, encrypted); printf("Encrypted: %s\n", ip_str); /* Decrypt */ crypto_ipcrypt_decrypt(decrypted, encrypted, key); /* Convert back to string */ sodium_bin2ip(ip_str, sizeof ip_str, decrypted); printf("Decrypted: %s\n", ip_str); /* \"192.0.2.1\" */ return 0; } ``` -------------------------------- ### Install libsodium using vcpkg on Windows Source: https://github.com/jedisct1/libsodium-doc/blob/master/installation/README.md Steps to install libsodium on Windows using the vcpkg dependency manager. This method automates the build and integration process. ```batch git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.bat ./vcpkg install libsodium ./vcpkg integrate install ``` -------------------------------- ### Public-key signatures: Multi-part message example Source: https://github.com/jedisct1/libsodium-doc/blob/master/public-key_cryptography/public-key_signatures.md Demonstrates signing and verifying a message composed of multiple parts using an incremental approach. ```c #define MESSAGE_PART1 \ ((const unsigned char *) "Arbitrary data to hash") #define MESSAGE_PART1_LEN 22 #define MESSAGE_PART2 \ ((const unsigned char *) "is longer than expected") #define MESSAGE_PART2_LEN 23 unsigned char pk[crypto_sign_PUBLICKEYBYTES]; unsigned char sk[crypto_sign_SECRETKEYBYTES]; crypto_sign_keypair(pk, sk); crypto_sign_state state; unsigned char sig[crypto_sign_BYTES]; /* signature creation */ crypto_sign_init(&state) crypto_sign_update(&state, MESSAGE_PART1, MESSAGE_PART1_LEN); crypto_sign_update(&state, MESSAGE_PART2, MESSAGE_PART2_LEN); crypto_sign_final_create(&state, sig, NULL, sk); /* signature verification */ crypto_sign_init(&state) crypto_sign_update(&state, MESSAGE_PART1, MESSAGE_PART1_LEN); crypto_sign_update(&state, MESSAGE_PART2, MESSAGE_PART2_LEN); if (crypto_sign_final_verify(&state, sig, pk) != 0) { /* message forged! */ } ``` -------------------------------- ### Generic Hashing - Single-part example with a key Source: https://github.com/jedisct1/libsodium-doc/blob/master/hashing/generic_hashing.md Demonstrates how to compute a hash for a message using a key. ```APIDOC ## Generic Hashing - Single-part example with a key ### Description Computes a hash for a message using a provided cryptographic key. ### Method `crypto_generichash` ### Endpoint N/A (This is a library function, not a network endpoint) ### Parameters #### Input - `out` (unsigned char *) - Output buffer for the hash. - `outlen` (size_t) - Length of the output buffer. - `in` (const unsigned char *) - The message to hash. - `inlen` (unsigned long long) - The length of the message. - `key` (const unsigned char *) - The cryptographic key. - `keylen` (size_t) - The length of the key. ### Request Example ```c #define MESSAGE ((const unsigned char *) "Arbitrary data to hash") #define MESSAGE_LEN 22 unsigned char hash[crypto_generichash_BYTES]; unsigned char key[crypto_generichash_KEYBYTES]; randombytes_buf(key, sizeof key); crypto_generichash(hash, sizeof hash, MESSAGE, MESSAGE_LEN, key, sizeof key); ``` ### Response #### Success Response (0) - `out` buffer will contain the computed hash. #### Response Example (The content of the `hash` buffer after execution) ``` -------------------------------- ### Multi-Part SHA-256 Hashing Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/sha-2_hash_function.md Illustrates hashing a message in multiple parts using the streaming API. Initialize the state, update with message chunks, and finalize to get the hash. The state must be reinitialized if reused. ```c #define MESSAGE_PART1 \ ((const unsigned char *) "Arbitrary data to hash") #define MESSAGE_PART1_LEN 22 #define MESSAGE_PART2 \ ((const unsigned char *) "is longer than expected") #define MESSAGE_PART2_LEN 23 unsigned char out[crypto_hash_sha256_BYTES]; crypto_hash_sha256_state state; crypto_hash_sha256_init(&state); crypto_hash_sha256_update(&state, MESSAGE_PART1, MESSAGE_PART1_LEN); crypto_hash_sha256_update(&state, MESSAGE_PART2, MESSAGE_PART2_LEN); crypto_hash_sha256_final(&state, out); ``` -------------------------------- ### Public-key Authenticated Encryption Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/public-key_cryptography/authenticated_encryption.md This example demonstrates the complete process of public-key authenticated encryption, including key pair generation, message encryption, and decryption. ```APIDOC ## Public-key Authenticated Encryption Example ### Description This example demonstrates the complete process of public-key authenticated encryption, including key pair generation, message encryption, and decryption. ### Method N/A (Illustrative C code) ### Endpoint N/A ### Request Example ```c #define MESSAGE (const unsigned char *) "test" #define MESSAGE_LEN 4 #define CIPHERTEXT_LEN (crypto_box_MACBYTES + MESSAGE_LEN) unsigned char alice_publickey[crypto_box_PUBLICKEYBYTES]; unsigned char alice_secretkey[crypto_box_SECRETKEYBYTES]; crypto_box_keypair(alice_publickey, alice_secretkey); unsigned char bob_publickey[crypto_box_PUBLICKEYBYTES]; unsigned char bob_secretkey[crypto_box_SECRETKEYBYTES]; crypto_box_keypair(bob_publickey, bob_secretkey); unsigned char nonce[crypto_box_NONCEBYTES]; unsigned char ciphertext[CIPHERTEXT_LEN]; randombytes_buf(nonce, sizeof nonce); if (crypto_box_easy(ciphertext, MESSAGE, MESSAGE_LEN, nonce, bob_publickey, alice_secretkey) != 0) { /* error */ } unsigned char decrypted[MESSAGE_LEN]; if (crypto_box_open_easy(decrypted, ciphertext, CIPHERTEXT_LEN, nonce, alice_publickey, bob_secretkey) != 0) { /* message for Bob pretending to be from Alice has been forged! */ } ``` ### Response N/A (Illustrative C code) ``` -------------------------------- ### Generic Hashing - Multi-part example with a key Source: https://github.com/jedisct1/libsodium-doc/blob/master/hashing/generic_hashing.md Demonstrates how to compute a hash for a message that is processed in multiple parts, using a key. ```APIDOC ## Generic Hashing - Multi-part example with a key ### Description Computes a hash for a message by processing it in multiple chunks, using a cryptographic key. This is useful for large messages or streams. ### Method `crypto_generichash_init`, `crypto_generichash_update`, `crypto_generichash_final` ### Endpoint N/A (This is a library function, not a network endpoint) ### Parameters #### Initialization (`crypto_generichash_init`) - `state` (crypto_generichash_state *) - Pointer to the state structure. - `key` (const unsigned char *) - The cryptographic key (can be NULL). - `keylen` (size_t) - The length of the key. - `outlen` (size_t) - The desired length of the output hash. #### Update (`crypto_generichash_update`) - `state` (crypto_generichash_state *) - Pointer to the initialized state structure. - `in` (const unsigned char *) - Pointer to the message chunk. - `inlen` (unsigned long long) - The length of the message chunk. #### Finalization (`crypto_generichash_final`) - `state` (crypto_generichash_state *) - Pointer to the state structure after all updates. - `out` (unsigned char *) - Output buffer for the final hash. - `outlen` (size_t) - The length of the output buffer. ### Request Example ```c #define MESSAGE_PART1 \ ((const unsigned char *) "Arbitrary data to hash") #define MESSAGE_PART1_LEN 22 #define MESSAGE_PART2 \ ((const unsigned char *) "is longer than expected") #define MESSAGE_PART2_LEN 23 unsigned char hash[crypto_generichash_BYTES]; unsigned char key[crypto_generichash_KEYBYTES]; crypto_generichash_state state; randombytes_buf(key, sizeof key); crypto_generichash_init(&state, key, sizeof key, sizeof hash); crypto_generichash_update(&state, MESSAGE_PART1, MESSAGE_PART1_LEN); crypto_generichash_update(&state, MESSAGE_PART2, MESSAGE_PART2_LEN); crypto_generichash_final(&state, hash, sizeof hash); ``` ### Response #### Success Response (0) - `out` buffer will contain the computed hash after all parts are processed. #### Response Example (The content of the `hash` buffer after `crypto_generichash_final`) ``` -------------------------------- ### Compile and Install on Unix-like Systems Source: https://github.com/jedisct1/libsodium-doc/blob/master/installation/README.md Standard procedure for compiling and installing libsodium on Unix-like systems using Autotools. Ensure to run 'make check' for verification. ```sh ./configure make && make check sudo make install ``` -------------------------------- ### Single-part HMAC Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/hmac-sha2.md Example demonstrating the single-part HMAC-SHA-512 usage. ```APIDOC ## Single-part HMAC Example ### Description This example demonstrates how to compute an HMAC-SHA-512 hash for a message using a single function call. ### Code ```c #define MESSAGE ((const unsigned char *) "Arbitrary data to hash") #define MESSAGE_LEN 22 unsigned char hash[crypto_auth_hmacsha512_BYTES]; unsigned char key[crypto_auth_hmacsha512_KEYBYTES]; crypto_auth_hmacsha512_keygen(key); crypto_auth_hmacsha512(hash, MESSAGE, MESSAGE_LEN, key); ``` ``` -------------------------------- ### Install haveged for Entropy Improvement Source: https://github.com/jedisct1/libsodium-doc/blob/master/usage/README.md On Linux systems with low entropy, installing `haveged` can help mitigate `sodium_init()` stalling. This is a workaround for kernels older than 5.4. ```sh apt-get install haveged ``` -------------------------------- ### Ristretto255 Secure Two-Party Computation Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/ristretto.md Example demonstrating a secure two-party computation of f(x) = p(x)^k using Ristretto255. ```APIDOC ## Ristretto255 Secure Two-Party Computation Example ### Description This example demonstrates a secure two-party computation of `f(x) = p(x)^k`. The first party sends a blinded `p(x)` after blinding it with a random scalar `r`. The second party computes and returns `g^k` and `a^k` (where `a = p(x) * g^r`). The first party then unblinds the result to obtain `f(x) = p(x)^k`. ### Code Example ```c // -------- First party -------- Send blinded p(x) unsigned char x[crypto_core_ristretto255_HASHBYTES]; randombytes_buf(x, sizeof x); // Compute px = p(x), a group element derived from x unsigned char px[crypto_core_ristretto255_BYTES]; crypto_core_ristretto255_from_hash(px, x); // Compute a = p(x) * g^r unsigned char r[crypto_core_ristretto255_SCALARBYTES]; unsigned char gr[crypto_core_ristretto255_BYTES]; unsigned char a[crypto_core_ristretto255_BYTES]; crypto_core_ristretto255_scalar_random(r); crypto_scalarmult_ristretto255_base(gr, r); crypto_core_ristretto255_add(a, px, gr); // -------- Second party -------- Send g^k and a^k unsigned char k[crypto_core_ristretto255_SCALARBYTES]; unsigned char v[crypto_core_ristretto255_BYTES]; // g^k unsigned char b[crypto_core_ristretto255_BYTES]; // a^k crypto_core_ristretto255_scalar_random(k); crypto_scalarmult_ristretto255_base(v, k); if (crypto_scalarmult_ristretto255(b, k, a) != 0) { return -1; } // -------- First party -------- Unblind f(x) // Compute vir = v^(-r) unsigned char ir[crypto_core_ristretto255_SCALARBYTES]; unsigned char vir[crypto_core_ristretto255_BYTES]; crypto_core_ristretto255_scalar_negate(ir, r); crypto_scalarmult_ristretto255(vir, ir, v); // Compute f(x) = b * v^(-r) = (p(x) * g^r)^k * (g^k)^(-r) // = (p(x) * g)^k * g^(-k) = p(x)^k unsigned char fx[crypto_core_ristretto255_BYTES]; crypto_core_ristretto255_add(fx, b, vir); ``` ``` -------------------------------- ### PFX Encryption Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/ip_address_encryption/README.md Demonstrates generating a key, encrypting two IP addresses within the same /24 subnet using PFX mode, and printing the results. Requires `sodium_ip2bin` and `sodium_bin2ip`. ```c unsigned char key[crypto_ipcrypt_PFX_KEYBYTES]; unsigned char addr1[crypto_ipcrypt_PFX_BYTES]; unsigned char addr2[crypto_ipcrypt_PFX_BYTES]; unsigned char enc1[crypto_ipcrypt_PFX_BYTES]; unsigned char enc2[crypto_ipcrypt_PFX_BYTES]; char ip_str[46]; crypto_ipcrypt_pfx_keygen(key); /* Encrypt two addresses in the same /24 */ if (sodium_ip2bin(addr1, "10.0.0.1", strlen("10.0.0.1")) != 0) { /* handle error */ } if (sodium_ip2bin(addr2, "10.0.0.100", strlen("10.0.0.100")) != 0) { /* handle error */ } crypto_ipcrypt_pfx_encrypt(enc1, addr1, key); crypto_ipcrypt_pfx_encrypt(enc2, addr2, key); sodium_bin2ip(ip_str, sizeof ip_str, enc1); printf("10.0.0.1 -> %s\n", ip_str); /* e.g., "79.55.98.17" */ sodium_bin2ip(ip_str, sizeof ip_str, enc2); printf("10.0.0.100 -> %s\n", ip_str); /* e.g., "79.55.98.127" - same /24 */ ``` -------------------------------- ### Example: Non-Deterministic IP Encryption Source: https://github.com/jedisct1/libsodium-doc/blob/master/ip_address_encryption/README.md Illustrates generating a key, creating a random tweak, parsing an IP, encrypting it non-deterministically, and then decrypting it. Assumes necessary libsodium functions like randombytes_buf are available. ```c unsigned char key[crypto_ipcrypt_ND_KEYBYTES]; unsigned char tweak[crypto_ipcrypt_ND_TWEAKBYTES]; unsigned char addr[crypto_ipcrypt_ND_INPUTBYTES]; unsigned char encrypted[crypto_ipcrypt_ND_OUTPUTBYTES]; unsigned char decrypted[crypto_ipcrypt_ND_INPUTBYTES]; char ip_str[46]; crypto_ipcrypt_nd_keygen(key); randombytes_buf(tweak, sizeof tweak); if (sodium_ip2bin(addr, "192.0.2.1", strlen("192.0.2.1")) != 0) { /* handle error */ } crypto_ipcrypt_nd_encrypt(encrypted, addr, tweak, key); crypto_ipcrypt_nd_decrypt(decrypted, encrypted, key); sodium_bin2ip(ip_str, sizeof ip_str, decrypted); /* \"192.0.2.1\" */ ``` -------------------------------- ### NDX Encryption Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/ip_address_encryption/README.md Demonstrates generating a key, setting up variables, encrypting an IP address, and decrypting it using NDX mode. Requires libsodium's `randombytes_buf`, `sodium_ip2bin`, and `sodium_bin2ip`. ```c unsigned char key[crypto_ipcrypt_NDX_KEYBYTES]; unsigned char tweak[crypto_ipcrypt_NDX_TWEAKBYTES]; unsigned char addr[crypto_ipcrypt_NDX_INPUTBYTES]; unsigned char encrypted[crypto_ipcrypt_NDX_OUTPUTBYTES]; unsigned char decrypted[crypto_ipcrypt_NDX_INPUTBYTES]; char ip_str[46]; crypto_ipcrypt_ndx_keygen(key); randombytes_buf(tweak, sizeof tweak); if (sodium_ip2bin(addr, "2001:db8::1", strlen("2001:db8::1")) != 0) { /* handle error */ } crypto_ipcrypt_ndx_encrypt(encrypted, addr, tweak, key); crypto_ipcrypt_ndx_decrypt(decrypted, encrypted, key); sodium_bin2ip(ip_str, sizeof ip_str, decrypted); /* "2001:db8::1" */ ``` -------------------------------- ### Public-key signatures: Combined mode example Source: https://github.com/jedisct1/libsodium-doc/blob/master/public-key_cryptography/public-key_signatures.md Generates a key pair, signs a message, and verifies the signature. The signed message includes the original message. ```c #define MESSAGE (const unsigned char *) "test" #define MESSAGE_LEN 4 unsigned char pk[crypto_sign_PUBLICKEYBYTES]; unsigned char sk[crypto_sign_SECRETKEYBYTES]; crypto_sign_keypair(pk, sk); unsigned char signed_message[crypto_sign_BYTES + MESSAGE_LEN]; unsigned long long signed_message_len; crypto_sign(signed_message, &signed_message_len, MESSAGE, MESSAGE_LEN, sk); unsigned char unsigned_message[MESSAGE_LEN]; unsigned long long unsigned_message_len; if (crypto_sign_open(unsigned_message, &unsigned_message_len, signed_message, signed_message_len, pk) != 0) { /* incorrect signature! */ } ``` -------------------------------- ### Generic Hashing - Single-part example without a key Source: https://github.com/jedisct1/libsodium-doc/blob/master/hashing/generic_hashing.md Demonstrates how to compute a hash for a message without using a key. ```APIDOC ## Generic Hashing - Single-part example without a key ### Description Computes a hash for a message without using a cryptographic key. ### Method `crypto_generichash` ### Endpoint N/A (This is a library function, not a network endpoint) ### Parameters #### Input - `out` (unsigned char *) - Output buffer for the hash. - `outlen` (size_t) - Length of the output buffer. - `in` (const unsigned char *) - The message to hash. - `inlen` (unsigned long long) - The length of the message. - `key` (const unsigned char *) - `NULL` for no key. - `keylen` (size_t) - `0` when `key` is `NULL`. ### Request Example ```c #define MESSAGE ((const unsigned char *) "Arbitrary data to hash") #define MESSAGE_LEN 22 unsigned char hash[crypto_generichash_BYTES]; crypto_generichash(hash, sizeof hash, MESSAGE, MESSAGE_LEN, NULL, 0); ``` ### Response #### Success Response (0) - `out` buffer will contain the computed hash. #### Response Example (The content of the `hash` buffer after execution) ``` -------------------------------- ### ML-KEM768 Key Encapsulation Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/ml-kem768.md Demonstrates the basic usage of ML-KEM768 for key pair generation, encapsulation, and decapsulation. Ensure proper error handling for production code. ```c unsigned char pk[crypto_kem_mlkem768_PUBLICKEYBYTES]; unsigned char sk[crypto_kem_mlkem768_SECRETKEYBYTES]; unsigned char ciphertext[crypto_kem_mlkem768_CIPHERTEXTBYTES]; unsigned char client_key[crypto_kem_mlkem768_SHAREDSECRETBYTES]; unsigned char server_key[crypto_kem_mlkem768_SHAREDSECRETBYTES]; crypto_kem_mlkem768_keypair(pk, sk); if (crypto_kem_mlkem768_enc(ciphertext, client_key, pk) != 0) { /* error */ } if (crypto_kem_mlkem768_dec(server_key, ciphertext, sk) != 0) { /* error */ } ``` -------------------------------- ### Pad and Unpad Buffer Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/helpers/padding.md Demonstrates how to use `sodium_pad` to round a buffer's length to a multiple of a block size and `sodium_unpad` to retrieve the original length. Ensure the buffer is large enough to prevent overflow. ```c unsigned char buf[100]; size_t buf_unpadded_len = 10; size_t buf_padded_len; size_t block_size = 16; /* round the length of the buffer to a multiple of `block_size` by appending * padding data and put the new, total length into `buf_padded_len` */ if (sodium_pad(&buf_padded_len, buf, buf_unpadded_len, block_size, sizeof buf) != 0) { /* overflow! buf[] is not large enough */ } /* compute the original, unpadded length */ if (sodium_unpad(&buf_unpadded_len, buf, buf_padded_len, block_size) != 0) { /* incorrect padding */ } ``` -------------------------------- ### Generate and verify authentication tag Source: https://github.com/jedisct1/libsodium-doc/blob/master/secret-key_cryptography/secret-key_authentication.md This example demonstrates generating an authentication tag for a message using a secret key and then verifying that tag. Ensure the key is kept confidential. The key is generated using `crypto_auth_keygen`. ```c #define MESSAGE (const unsigned char *) "test" #define MESSAGE_LEN 4 unsigned char key[crypto_auth_KEYBYTES]; unsigned char mac[crypto_auth_BYTES]; crypto_auth_keygen(key); crypto_auth(mac, MESSAGE, MESSAGE_LEN, key); if (crypto_auth_verify(mac, MESSAGE, MESSAGE_LEN, key) != 0) { /* message forged! */ } ``` -------------------------------- ### Multi-part SHA-256 Hashing (Streaming) Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/sha-2_hash_function.md Example demonstrating how to compute the SHA-256 hash of a message using a streaming API, processing the message in chunks. ```APIDOC ## Multi-part SHA-256 Hashing (Streaming) ### Description Computes the SHA-256 hash of a message by processing it in multiple parts or chunks. ### Method - `crypto_hash_sha256_init(crypto_hash_sha256_state *state)`: Initializes the SHA-256 state. - `crypto_hash_sha256_update(crypto_hash_sha256_state *state, const unsigned char *in, unsigned long long inlen)`: Updates the hash state with a chunk of data. - `crypto_hash_sha256_final(crypto_hash_sha256_state *state, unsigned char *out)`: Finalizes the hash computation and returns the result. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c #define MESSAGE_PART1 ((const unsigned char *) "Arbitrary data to hash") #define MESSAGE_PART1_LEN 22 #define MESSAGE_PART2 ((const unsigned char *) "is longer than expected") #define MESSAGE_PART2_LEN 23 unsigned char out[crypto_hash_sha256_BYTES]; crypto_hash_sha256_state state; crypto_hash_sha256_init(&state); crypto_hash_sha256_update(&state, MESSAGE_PART1, MESSAGE_PART1_LEN); crypto_hash_sha256_update(&state, MESSAGE_PART2, MESSAGE_PART2_LEN); crypto_hash_sha256_final(&state, out); ``` ### Response #### Success Response (200) - **out** (unsigned char array) - The computed SHA-256 hash. The size is defined by `crypto_hash_sha256_BYTES`. #### Response Example (Binary data representing the hash) ``` -------------------------------- ### Finite Field Arithmetic Example: Secure Two-Party Computation Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/point-arithmetic.md An example demonstrating a secure two-party computation of f(x) = p(x)^k using libsodium's ed25519 core functions. This involves blinding inputs, secret key operations, and unblinding the final result. ```APIDOC ## Secure Two-Party Computation Example ### Description This example illustrates a secure two-party computation scenario where the first party computes `p(x)^k` without knowing `k`, and the second party computes it without knowing `x`. `p(x)` is a hash-to-curve function, `x` is the input, and `k` is a secret key. ### First Party: Send blinded p(x) ```c // -------- First party -------- Send blinded p(x) unsigned char x[crypto_core_ed25519_UNIFORMBYTES]; randombytes_buf(x, sizeof x); // Compute px = p(x), an EC point representative for x unsigned char px[crypto_core_ed25519_BYTES]; crypto_core_ed25519_from_uniform(px, x); // Compute a = p(x) * g^r unsigned char r[crypto_core_ed25519_SCALARBYTES]; unsigned char gr[crypto_core_ed25519_BYTES]; unsigned char a[crypto_core_ed25519_BYTES]; crypto_core_ed25519_scalar_random(r); crypto_scalarmult_ed25519_base_noclamp(gr, r); crypto_core_ed25519_add(a, px, gr); ``` ### Second Party: Send g^k and a^k ```c // -------- Second party -------- Send g^k and a^k unsigned char k[crypto_core_ed25519_SCALARBYTES]; randombytes_buf(k, sizeof k); // Compute v = g^k unsigned char v[crypto_core_ed25519_BYTES]; crypto_scalarmult_ed25519_base(v, k); // Compute b = a^k unsigned char b[crypto_core_ed25519_BYTES]; if (crypto_scalarmult_ed25519(b, k, a) != 0) { return -1; } ``` ### First Party: Unblind f(x) ```c // -------- First party -------- Unblind f(x) // Compute vir = v^(-r) unsigned char ir[crypto_core_ed25519_SCALARBYTES]; unsigned char vir[crypto_core_ed25519_BYTES]; crypto_core_ed25519_scalar_negate(ir, r); crypto_scalarmult_ed25519_noclamp(vir, ir, v); // Compute f(x) = b * v^(-r) = (p(x) * g^r)^k * (g^k)^(-r) // = (p(x) * g)^k * g^(-k) = p(x)^k unsigned char fx[crypto_core_ed25519_BYTES]; crypto_core_ed25519_add(fx, b, vir); ``` ``` -------------------------------- ### Multi-part SHA-512 Hashing (Streaming) Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/sha-2_hash_function.md Example demonstrating how to compute the SHA-512 hash of a message using a streaming API, processing the message in chunks. ```APIDOC ## Multi-part SHA-512 Hashing (Streaming) ### Description Computes the SHA-512 hash of a message by processing it in multiple parts or chunks. ### Method - `crypto_hash_sha512_init(crypto_hash_sha512_state *state)`: Initializes the SHA-512 state. - `crypto_hash_sha512_update(crypto_hash_sha512_state *state, const unsigned char *in, unsigned long long inlen)`: Updates the hash state with a chunk of data. - `crypto_hash_sha512_final(crypto_hash_sha512_state *state, unsigned char *out)`: Finalizes the hash computation and returns the result. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c // Example usage for SHA-512 multi-part hashing would be similar to SHA-256, // replacing crypto_hash_sha256_* functions with their SHA-512 counterparts. // For instance: // crypto_hash_sha512_state state; // crypto_hash_sha512_init(&state); // crypto_hash_sha512_update(&state, chunk1, chunk1_len); // crypto_hash_sha512_update(&state, chunk2, chunk2_len); // crypto_hash_sha512_final(&state, out); ``` ### Response #### Success Response (200) - **out** (unsigned char array) - The computed SHA-512 hash. The size is defined by `crypto_hash_sha512_BYTES`. #### Response Example (Binary data representing the hash) ``` -------------------------------- ### Keccak-f[1600] Permutation Usage Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/keccak1600.md Demonstrates the sponge construction pattern: initialize, absorb data, and squeeze output. Call permute_24() or permute_12() after absorbing a block. ```c crypto_core_keccak1600_state state; /* Initialize */ crypto_core_keccak1600_init(&state); /* Absorb: XOR data into state and permute */ crypto_core_keccak1600_xor_bytes(&state, input, 0, input_len); crypto_core_keccak1600_permute_24(&state); /* Squeeze: extract output from state */ crypto_core_keccak1600_extract_bytes(&state, output, 0, output_len); ``` -------------------------------- ### Single-part SHA3-256 Hashing Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/sha-3_hash_function.md Demonstrates how to compute the SHA3-256 hash of a message in a single operation. Ensure the message and its length are correctly defined. ```c #define MESSAGE ((const unsigned char *) "test") #define MESSAGE_LEN 4 unsigned char out[crypto_hash_sha3256_BYTES]; crypto_hash_sha3256(out, MESSAGE, MESSAGE_LEN); ``` -------------------------------- ### Single-part SHA-256 Hashing Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/sha-2_hash_function.md Example demonstrating how to compute the SHA-256 hash of a message in a single pass. ```APIDOC ## Single-part SHA-256 Hashing ### Description Computes the SHA-256 hash of a given message in a single operation. ### Method `crypto_hash_sha256(unsigned char *out, const unsigned char *in, unsigned long long inlen)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c #define MESSAGE ((const unsigned char *) "test") #define MESSAGE_LEN 4 unsigned char out[crypto_hash_sha256_BYTES]; crypto_hash_sha256(out, MESSAGE, MESSAGE_LEN); ``` ### Response #### Success Response (200) - **out** (unsigned char array) - The computed SHA-256 hash. The size is defined by `crypto_hash_sha256_BYTES`. #### Response Example (Binary data representing the hash) ``` -------------------------------- ### Encrypt and Decrypt a Sealed Box Message Source: https://github.com/jedisct1/libsodium-doc/blob/master/public-key_cryptography/sealed_boxes.md This example demonstrates the complete process of creating a key pair, encrypting a message using crypto_box_seal, and then decrypting it with crypto_box_seal_open. Ensure the ciphertext is not corrupted and is intended for the recipient. ```c #define MESSAGE (const unsigned char *) "Message" #define MESSAGE_LEN 7 #define CIPHERTEXT_LEN (crypto_box_SEALBYTES + MESSAGE_LEN) /* Recipient creates a long-term key pair */ unsigned char recipient_pk[crypto_box_PUBLICKEYBYTES]; unsigned char recipient_sk[crypto_box_SECRETKEYBYTES]; crypto_box_keypair(recipient_pk, recipient_sk); /* Anonymous sender encrypts a message using an ephemeral key pair * and the recipient's public key */ unsigned char ciphertext[CIPHERTEXT_LEN]; crypto_box_seal(ciphertext, MESSAGE, MESSAGE_LEN, recipient_pk); /* Recipient decrypts the ciphertext */ unsigned char decrypted[MESSAGE_LEN]; if (crypto_box_seal_open(decrypted, ciphertext, CIPHERTEXT_LEN, recipient_pk, recipient_sk) != 0) { /* message corrupted or not intended for this recipient */ } ``` -------------------------------- ### Single-Part SHA-256 Hashing Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/sha-2_hash_function.md Demonstrates how to compute the SHA-256 hash of a message in a single operation. Ensure the message and its length are correctly defined. ```c #define MESSAGE ((const unsigned char *) "test") #define MESSAGE_LEN 4 unsigned char out[crypto_hash_sha256_BYTES]; crypto_hash_sha256(out, MESSAGE, MESSAGE_LEN); ``` -------------------------------- ### Single-part SHA3-512 Hashing Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/sha-3_hash_function.md Shows how to calculate the SHA3-512 hash of a message using a single function call. Define the message and its length accurately. ```c #define MESSAGE ((const unsigned char *) "test") #define MESSAGE_LEN 4 unsigned char out[crypto_hash_sha3512_BYTES]; crypto_hash_sha3512(out, MESSAGE, MESSAGE_LEN); ``` -------------------------------- ### AES-GCM Encryption and Decryption Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/secret-key_cryptography/aes-256-gcm.md Demonstrates encrypting a message with additional data and then decrypting it using AES-GCM. Ensure the CPU supports AES-NI or ARM Crypto extensions and that libsodium is initialized with sodium_init(). Nonces must be unique for each encryption with the same key. ```c #include #define MESSAGE (const unsigned char *) "test" #define MESSAGE_LEN 4 #define ADDITIONAL_DATA (const unsigned char *) "123456" #define ADDITIONAL_DATA_LEN 6 unsigned char nonce[crypto_aead_aes256gcm_NPUBBYTES]; unsigned char key[crypto_aead_aes256gcm_KEYBYTES]; unsigned char ciphertext[MESSAGE_LEN + crypto_aead_aes256gcm_ABYTES]; unsigned long long ciphertext_len; sodium_init(); if (crypto_aead_aes256gcm_is_available() == 0) { abort(); /* Not available on this CPU */ } crypto_aead_aes256gcm_keygen(key); randombytes_buf(nonce, sizeof nonce); crypto_aead_aes256gcm_encrypt(ciphertext, &ciphertext_len, MESSAGE, MESSAGE_LEN, ADDITIONAL_DATA, ADDITIONAL_DATA_LEN, NULL, nonce, key); unsigned char decrypted[MESSAGE_LEN]; unsigned long long decrypted_len; if (ciphertext_len < crypto_aead_aes256gcm_ABYTES || crypto_aead_aes256gcm_decrypt(decrypted, &decrypted_len, NULL, ciphertext, ciphertext_len, ADDITIONAL_DATA, ADDITIONAL_DATA_LEN, nonce, key) != 0) { /* message forged! */ } ``` -------------------------------- ### TurboSHAKE128 Hashing, Key Derivation, and Randomness Generation Source: https://github.com/jedisct1/libsodium-doc/blob/master/hashing/xof.md Provides examples of using TurboSHAKE128 for generating a 256-bit hash, deriving a 256-bit key, and generating 1KB of deterministic randomness. The output length does not affect preimage resistance for key derivation or PRF use cases. ```c /* TurboSHAKE128 producing a 256-bit hash - full 128-bit security */ unsigned char hash[32]; crypto_xof_turboshake128(hash, 32, message, message_len); /* TurboSHAKE128 deriving a 256-bit key - full 128-bit security */ unsigned char key[32]; crypto_xof_turboshake128(key, 32, seed, seed_len); /* TurboSHAKE128 generating 1KB of deterministic randomness */ unsigned char random_data[1024]; crypto_xof_turboshake128(random_data, 1024, seed, seed_len); ``` -------------------------------- ### Secure Two-Party Computation Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/point-arithmetic.md Demonstrates a secure two-party computation of f(x) = p(x)^k. The first party sends a blinded input, and the second party uses a secret key. Requires libsodium crypto functions. ```c // -------- First party -------- Send blinded p(x) unsigned char x[crypto_core_ed25519_UNIFORMBYTES]; randombytes_buf(x, sizeof x); // Compute px = p(x), an EC point representative for x unsigned char px[crypto_core_ed25519_BYTES]; crypto_core_ed25519_from_uniform(px, x); // Compute a = p(x) * g^r unsigned char r[crypto_core_ed25519_SCALARBYTES]; unsigned char gr[crypto_core_ed25519_BYTES]; unsigned char a[crypto_core_ed25519_BYTES]; crypto_core_ed25519_scalar_random(r); crypto_scalarmult_ed25519_base_noclamp(gr, r); crypto_core_ed25519_add(a, px, gr); // -------- Second party -------- Send g^k and a^k unsigned char k[crypto_core_ed25519_SCALARBYTES]; randombytes_buf(k, sizeof k); // Compute v = g^k unsigned char v[crypto_core_ed25519_BYTES]; crypto_scalarmult_ed25519_base(v, k); // Compute b = a^k unsigned char b[crypto_core_ed25519_BYTES]; if (crypto_scalarmult_ed25519(b, k, a) != 0) { return -1; } // -------- First party -------- Unblind f(x) // Compute vir = v^(-r) unsigned char ir[crypto_core_ed25519_SCALARBYTES]; unsigned char vir[crypto_core_ed25519_BYTES]; crypto_core_ed25519_scalar_negate(ir, r); crypto_scalarmult_ed25519_noclamp(vir, ir, v); // Compute f(x) = b * v^(-r) = (p(x) * g^r)^k * (g^k)^(-r) // = (p(x) * g)^k * g^(-k) = p(x)^k unsigned char fx[crypto_core_ed25519_BYTES]; crypto_core_ed25519_add(fx, b, vir); ``` -------------------------------- ### HMAC-SHA-512 Multi-Part Example Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/hmac-sha2.md Generates an HMAC-SHA-512 hash for a message processed in multiple parts using a streaming API. Initializes a state, updates it with message parts, and then finalizes to get the hash. ```c #define MESSAGE_PART1 \ ((const unsigned char *) "Arbitrary data to hash") #define MESSAGE_PART1_LEN 22 #define MESSAGE_PART2 \ ((const unsigned char *) "is longer than expected") #define MESSAGE_PART2_LEN 23 unsigned char hash[crypto_auth_hmacsha512_BYTES]; unsigned char key[crypto_auth_hmacsha512_KEYBYTES]; crypto_auth_hmacsha512_state state; crypto_auth_hmacsha512_keygen(key); crypto_auth_hmacsha512_init(&state, key, sizeof key); crypto_auth_hmacsha512_update(&state, MESSAGE_PART1, MESSAGE_PART1_LEN); crypto_auth_hmacsha512_update(&state, MESSAGE_PART2, MESSAGE_PART2_LEN); crypto_auth_hmacsha512_final(&state, hash); ``` -------------------------------- ### Initialize libsodium Library Source: https://github.com/jedisct1/libsodium-doc/blob/master/usage/README.md Include `sodium.h` and call `sodium_init()` before any other libsodium functions. It's safe to call multiple times. ```c #include int main(void) { if (sodium_init() == -1) { return 1; } ... } ``` -------------------------------- ### Install rng-tools for Entropy Improvement Source: https://github.com/jedisct1/libsodium-doc/blob/master/usage/README.md An alternative to `haveged` for improving random number generation entropy on Linux is to install `rng-tools`. Some environments may require the `-O jitter:timeout=20` option. ```sh apt-get install rng-tools ``` -------------------------------- ### Hashing with Context/Domain Separation Source: https://github.com/jedisct1/libsodium-doc/blob/master/hashing/xof.md Demonstrates how to use domain separators with XOFs to create distinct hashing contexts. Initialize the XOF with a specific domain ID before updating and squeezing. ```c #define DOMAIN_FILE_ID 0x01 #define DOMAIN_SESSION_ID 0x02 /* Hash a file with domain separation */ unsigned char file_hash[32]; crypto_xof_turboshake128_state state; crypto_xof_turboshake128_init_with_domain(&state, DOMAIN_FILE_ID); crypto_xof_turboshake128_update(&state, file_contents, file_len); crypto_xof_turboshake128_squeeze(&state, file_hash, sizeof file_hash); /* Hash session data - independent from file hashing even with same input */ unsigned char session_id[16]; crypto_xof_turboshake128_init_with_domain(&state, DOMAIN_SESSION_ID); crypto_xof_turboshake128_update(&state, session_data, session_len); crypto_xof_turboshake128_squeeze(&state, session_id, sizeof session_id); ``` -------------------------------- ### Single-part SHA-512 Hashing Source: https://github.com/jedisct1/libsodium-doc/blob/master/advanced/sha-2_hash_function.md Example demonstrating how to compute the SHA-512 hash of a message in a single pass. ```APIDOC ## Single-part SHA-512 Hashing ### Description Computes the SHA-512 hash of a given message in a single operation. ### Method `crypto_hash_sha512(unsigned char *out, const unsigned char *in, unsigned long long inlen)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c // Example usage for SHA-512 single-part hashing would be similar to SHA-256, // replacing crypto_hash_sha256 with crypto_hash_sha512 and adjusting output buffer size. // For instance: // unsigned char out[crypto_hash_sha512_BYTES]; // crypto_hash_sha512(out, message, message_len); ``` ### Response #### Success Response (200) - **out** (unsigned char array) - The computed SHA-512 hash. The size is defined by `crypto_hash_sha512_BYTES`. #### Response Example (Binary data representing the hash) ```