### Querying Documentation with GET Request Source: https://libsodium.gitbook.io/doc/advanced/sha-2_hash_function Demonstrates how to query the documentation dynamically by performing a GET request with an 'ask' query parameter. Use this for clarification or additional context. ```http GET https://libsodium.gitbook.io/doc/advanced/sha-2_hash_function.md?ask= ``` -------------------------------- ### Example: Deterministic IP Encryption and Decryption Source: https://libsodium.gitbook.io/doc/secret-key_cryptography/ip_address_encryption Demonstrates encrypting an IP address deterministically and then decrypting it back. This example requires libsodium initialization and uses helper functions for IP address conversion. ```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; } ``` -------------------------------- ### Query Documentation Source: https://libsodium.gitbook.io/doc/secret-key_cryptography/secret-key_authentication To get more information, make a GET request to the current page URL with an 'ask' query parameter containing your question. ```http GET https://libsodium.gitbook.io/doc/secret-key_cryptography/secret-key_authentication.md?ask= ``` -------------------------------- ### Install Libsodium using vcpkg on Windows Source: https://libsodium.gitbook.io/doc/installation 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 ``` -------------------------------- ### Compile and Install Libsodium on Unix-like Systems Source: https://libsodium.gitbook.io/doc/installation Standard compilation and installation process for libsodium on Unix-like systems using Autotools. Ensure you have the necessary build tools installed. ```sh ./configure make && make check sudo make install ``` -------------------------------- ### Key Encapsulation Example Source: https://libsodium.gitbook.io/doc/public-key_cryptography/key_encapsulation Demonstrates the complete key encapsulation process: key pair generation, encapsulation, and decapsulation. ```c 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]; crypto_kem_keypair(pk, sk); if (crypto_kem_enc(ciphertext, client_key, pk) != 0) { /* error */ } if (crypto_kem_dec(server_key, ciphertext, sk) != 0) { /* error */ } ``` -------------------------------- ### Install rng-tools for Entropy Improvement Source: https://libsodium.gitbook.io/doc/usage Alternatively, `rng-tools` can be installed to enhance the system's random number generation capabilities. ```sh apt-get install rng-tools ``` -------------------------------- ### PFX Encryption Example Source: https://libsodium.gitbook.io/doc/secret-key_cryptography/ip_address_encryption Example demonstrating PFX encryption of two IPv4 addresses within the same /24 subnet. Shows how encrypted addresses maintain the same prefix. Requires key generation, IP conversion, encryption, and binary-to-IP conversion. ```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 */ ``` -------------------------------- ### Query Documentation with GET Request Source: https://libsodium.gitbook.io/doc/hashing Use this method to ask questions about the documentation dynamically. The response includes answers and relevant excerpts. ```http GET https://libsodium.gitbook.io/doc/hashing.md?ask= ``` -------------------------------- ### Multi-part SHA3-256 Hashing Source: https://libsodium.gitbook.io/doc/advanced/sha-3_hash_function Example demonstrating how to compute a SHA3-256 hash for a message that is processed in multiple chunks using a streaming API. The state must be initialized before use and finalized to get the hash result. ```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); ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://libsodium.gitbook.io/doc/public-key_cryptography/authenticated_encryption To get additional information not directly present on the page, perform an HTTP GET request with an 'ask' query parameter. The question should be specific and self-contained. ```http GET https://libsodium.gitbook.io/doc/public-key_cryptography/authenticated_encryption.md?ask= ``` -------------------------------- ### Query Documentation Dynamically Source: https://libsodium.gitbook.io/doc/advanced/stream_ciphers/xchacha20 To get additional information not explicitly present on the page, perform an HTTP GET request with an 'ask' query parameter. The response will contain a direct answer and relevant excerpts. ```http GET https://libsodium.gitbook.io/doc/advanced/stream_ciphers/xchacha20.md?ask= ``` -------------------------------- ### Querying Documentation Dynamically Source: https://libsodium.gitbook.io/doc/advanced/scrypt To get additional information not directly present on the page, perform an HTTP GET request with the 'ask' query parameter. The question should be specific and self-contained. ```http GET https://libsodium.gitbook.io/doc/advanced/scrypt.md?ask= ``` -------------------------------- ### Querying Documentation Dynamically Source: https://libsodium.gitbook.io/doc/advanced/ml-kem768 To get additional information not directly on the page, perform an HTTP GET request to the current URL with the 'ask' query parameter. The question should be specific and self-contained. ```http GET https://libsodium.gitbook.io/doc/advanced/ml-kem768.md?ask= ``` -------------------------------- ### Query Documentation Dynamically Source: https://libsodium.gitbook.io/doc/advanced/stream_ciphers/chacha20 To get specific information not explicitly found on the page, make an HTTP GET request to the current URL with an 'ask' query parameter containing your question. The response will include a direct answer and relevant documentation excerpts. ```http GET https://libsodium.gitbook.io/doc/advanced/stream_ciphers/chacha20.md?ask= ``` -------------------------------- ### Querying Documentation Source: https://libsodium.gitbook.io/doc/hashing/short-input_hashing To get additional information not present on the page, perform an HTTP GET request with an 'ask' query parameter. The question should be specific and self-contained. ```http GET https://libsodium.gitbook.io/doc/hashing/short-input_hashing.md?ask= ``` -------------------------------- ### Example of sodium_pad and sodium_unpad Source: https://libsodium.gitbook.io/doc/padding Demonstrates how to use sodium_pad to add padding to a buffer and sodium_unpad to compute the original unpadded length. It includes error handling for buffer overflow and incorrect padding. ```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 */ } ``` -------------------------------- ### Query Documentation Dynamically Source: https://libsodium.gitbook.io/doc/public-key_cryptography Use this HTTP GET request to ask questions about the documentation. The 'ask' parameter should contain a specific, self-contained question in natural language. ```http GET https://libsodium.gitbook.io/doc/public-key_cryptography.md?ask= ``` -------------------------------- ### Query Documentation Dynamically Source: https://libsodium.gitbook.io/doc/advanced/stream_ciphers/xsalsa20 To get additional information not present on the page, make an HTTP GET request to the current page URL with an 'ask' query parameter containing your question. ```http GET https://libsodium.gitbook.io/doc/advanced/stream_ciphers/xsalsa20.md?ask= ``` -------------------------------- ### Generate and Verify Authentication Tag Source: https://libsodium.gitbook.io/doc/secret-key_cryptography/secret-key_authentication This example demonstrates how to generate an authentication tag for a message using a secret key and then verify its authenticity. Ensure the key and message are correctly defined. ```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! */ } ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://libsodium.gitbook.io/doc/libsodium_users Use this method to ask questions about the documentation. The question should be specific and self-contained. The response includes a direct answer and relevant excerpts. ```HTTP GET https://libsodium.gitbook.io/doc/libsodium_users.md?ask= ``` -------------------------------- ### Querying Documentation Dynamically Source: https://libsodium.gitbook.io/doc/password_hashing/default_phf To get additional information not directly present on the page, perform an HTTP GET request with the 'ask' query parameter. The question should be specific and in natural language. ```http GET https://libsodium.gitbook.io/doc/password_hashing/default_phf.md?ask= ``` -------------------------------- ### Install haveged for Entropy Improvement Source: https://libsodium.gitbook.io/doc/usage On Linux systems with low entropy, installing the `haveged` package can help improve the availability of random numbers. ```sh apt-get install haveged ``` -------------------------------- ### Sponge Construction: Squeeze Block Example Source: https://libsodium.gitbook.io/doc/advanced/keccak1600 Example function to extract a single block of output from the Keccak-f[1600] state using a specified rate and applying the permutation. Use `permute_24` for SHAKE or `permute_12` for TurboSHAKE. ```c void squeeze_block(crypto_core_keccak1600_state *state, unsigned char *block) { crypto_core_keccak1600_extract_bytes(state, block, 0, RATE); crypto_core_keccak1600_permute_24(state); /* or permute_12 for TurboSHAKE */ } ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://libsodium.gitbook.io/doc/hashing/xof Use this method to dynamically query the documentation. The question should be specific and self-contained. The response includes a direct answer and relevant excerpts. ```http GET https://libsodium.gitbook.io/doc/hashing/xof.md?ask= ``` -------------------------------- ### NDX Encryption and Decryption Example Source: https://libsodium.gitbook.io/doc/secret-key_cryptography/ip_address_encryption Example demonstrating NDX encryption and decryption of an IPv6 address. Requires key generation, random tweak generation, IP conversion, encryption, decryption, and binary-to-IP conversion. ```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" */ ``` -------------------------------- ### Querying Documentation Source: https://libsodium.gitbook.io/doc/password_hashing To get more information not present on the page, you can query the documentation dynamically using the `ask` query parameter. ```http GET https://libsodium.gitbook.io/doc/password_hashing.md?ask= ``` -------------------------------- ### Scrypt Key Derivation Example Source: https://libsodium.gitbook.io/doc/advanced/scrypt Derives a cryptographic key from a password and salt using scrypt. Ensure sufficient memory is available for the operation. ```c #define PASSWORD "Correct Horse Battery Staple" #define KEY_LEN crypto_box_SEEDBYTES unsigned char salt[crypto_pwhash_scryptsalsa208sha256_SALTBYTES]; unsigned char key[KEY_LEN]; randombytes_buf(salt, sizeof salt); if (crypto_pwhash_scryptsalsa208sha256 (key, sizeof key, PASSWORD, strlen(PASSWORD), salt, crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_INTERACTIVE, crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_INTERACTIVE) != 0) { /* out of memory */ } ``` -------------------------------- ### Query Documentation with 'ask' Parameter Source: https://libsodium.gitbook.io/doc/internals Perform an HTTP GET request to the current page URL with the 'ask' query parameter to dynamically query the documentation. The question should be specific and self-contained. ```http GET https://libsodium.gitbook.io/doc/internals.md?ask= ``` -------------------------------- ### Example: Non-Deterministic IP Encryption and Decryption Source: https://libsodium.gitbook.io/doc/secret-key_cryptography/ip_address_encryption Illustrates the process of non-deterministic IP encryption and decryption. This involves generating a key, a random tweak, encrypting the IP, and then decrypting it. ```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\" */ ``` -------------------------------- ### Enabling Sample ChaCha20-based RNG Source: https://libsodium.gitbook.io/doc/advanced/custom_rng Example of enabling a sample alternative `randombytes` implementation based on the ChaCha20 stream cipher. This should be called before `sodium_init()`. ```c randombytes_set_implementation(&randombytes_internal_implementation); ``` -------------------------------- ### Querying Documentation Dynamically Source: https://libsodium.gitbook.io/doc/advanced Perform an HTTP GET request to query the documentation dynamically. Use this when the answer is not explicitly present, for clarification, or to retrieve related documentation sections. ```http GET https://libsodium.gitbook.io/doc/advanced.md?ask= ``` -------------------------------- ### Deriving Multiple Outputs with TurboSHAKE Source: https://libsodium.gitbook.io/doc/hashing/xof When a uniformly random key is available and multiple outputs are needed, a XOF like TurboSHAKE offers a simpler alternative to multiple HKDF-Expand calls. This example shows how to initialize, update, and squeeze derived keys from a pseudorandom key and context. ```c /* Instead of multiple HKDF-Expand calls with different info strings, just squeeze the outputs you need */ unsigned char prk[32]; /* pseudorandom key from key exchange */ crypto_xof_turboshake128_state state; crypto_xof_turboshake128_init(&state); crypto_xof_turboshake128_update(&state, prk, sizeof prk); crypto_xof_turboshake128_update(&state, context, context_len); unsigned char derived[96]; /* 3 x 32-byte keys */ crypto_xof_turboshake128_squeeze(&state, derived, sizeof derived); ``` -------------------------------- ### Query Documentation Dynamically Source: https://libsodium.gitbook.io/doc/secret-key_cryptography/encrypted-messages Perform an HTTP GET request to query the documentation dynamically. Use this when the answer is not explicitly present, you need clarification, or want to retrieve related sections. ```http GET https://libsodium.gitbook.io/doc/secret-key_cryptography/encrypted-messages.md?ask= ``` -------------------------------- ### XChaCha20-Poly1305 Encryption and Decryption Example Source: https://libsodium.gitbook.io/doc/secret-key_cryptography/aead/chacha20-poly1305/xchacha20-poly1305_construction Demonstrates the combined mode of XChaCha20-Poly1305 for encrypting and decrypting a message with additional authenticated data. Requires libsodium to be initialized. ```c #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_xchacha20poly1305_ietf_NPUBBYTES]; unsigned char key[crypto_aead_xchacha20poly1305_ietf_KEYBYTES]; unsigned char ciphertext[MESSAGE_LEN + crypto_aead_xchacha20poly1305_ietf_ABYTES]; unsigned long long ciphertext_len; crypto_aead_xchacha20poly1305_ietf_keygen(key); randombytes_buf(nonce, sizeof nonce); crypto_aead_xchacha20poly1305_ietf_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 (crypto_aead_xchacha20poly1305_ietf_decrypt(decrypted, &decrypted_len, NULL, ciphertext, ciphertext_len, ADDITIONAL_DATA, ADDITIONAL_DATA_LEN, nonce, key) != 0) { /* message forged! */ } ``` -------------------------------- ### Key Derivation Example Source: https://libsodium.gitbook.io/doc/password_hashing/default_phf Derives a cryptographic key from a password using a salt and specified operational and memory limits. Ensure the salt is unpredictable and generated using randombytes_buf(). ```c #define PASSWORD "Correct Horse Battery Staple" #define KEY_LEN crypto_box_SEEDBYTES unsigned char salt[crypto_pwhash_SALTBYTES]; unsigned char key[KEY_LEN]; randombytes_buf(salt, sizeof salt); if (crypto_pwhash (key, sizeof key, PASSWORD, strlen(PASSWORD), salt, crypto_pwhash_OPSLIMIT_INTERACTIVE, crypto_pwhash_MEMLIMIT_INTERACTIVE, crypto_pwhash_ALG_DEFAULT) != 0) { /* out of memory */ } ``` -------------------------------- ### TurboSHAKE128 for Hashing, Key Derivation, and Randomness Source: https://libsodium.gitbook.io/doc/hashing/xof Examples of using TurboSHAKE128 for generating hashes, deriving keys, and producing deterministic random data. ```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); ``` -------------------------------- ### HMAC-SHA-512 Single-Part Example Source: https://libsodium.gitbook.io/doc/advanced/hmac-sha2 Demonstrates how to compute an HMAC-SHA-512 hash for a message using a single call. Requires key generation and the core authentication function. ```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); ``` -------------------------------- ### ML-KEM768 Keypair, Encapsulation, and Decapsulation Example Source: https://libsodium.gitbook.io/doc/advanced/ml-kem768 This snippet demonstrates the basic workflow of generating a key pair, encapsulating a shared secret, and then decapsulating it using the ML-KEM768 primitive. It includes error checking for the encapsulation and decapsulation steps. ```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 */ } ``` -------------------------------- ### Single-part SHA3-256 Hashing Source: https://libsodium.gitbook.io/doc/advanced/sha-3_hash_function Example demonstrating how to compute a SHA3-256 hash for a message in a single operation. Ensure the output buffer is large enough for the hash result. ```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); ``` -------------------------------- ### Multi-part SHA-256 Hashing Source: https://libsodium.gitbook.io/doc/advanced/sha-2_hash_function Example showing how to compute a SHA-256 hash of a message by processing it in multiple chunks using a streaming API. The state must be initialized before updating and finalized at the end. ```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); ``` -------------------------------- ### Single-part SHA-256 Hashing Source: https://libsodium.gitbook.io/doc/advanced/sha-2_hash_function Example demonstrating how to compute a SHA-256 hash of a message in a single operation. Ensure the message length is correctly specified. ```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); ``` -------------------------------- ### Scrypt Password Storage and Verification Example Source: https://libsodium.gitbook.io/doc/advanced/scrypt Stores a hashed password using scrypt and verifies a given password against the hash. This is suitable for sensitive data storage. ```c #define PASSWORD "Correct Horse Battery Staple" char hashed_password[crypto_pwhash_scryptsalsa208sha256_STRBYTES]; if (crypto_pwhash_scryptsalsa208sha256_str (hashed_password, PASSWORD, strlen(PASSWORD), crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_SENSITIVE, crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_SENSITIVE) != 0) { /* out of memory */ } if (crypto_pwhash_scryptsalsa208sha256_str_verify (hashed_password, PASSWORD, strlen(PASSWORD)) != 0) { /* wrong password */ } ``` -------------------------------- ### Password Storage and Verification Example Source: https://libsodium.gitbook.io/doc/password_hashing/default_phf Stores a password by hashing it into a string format and provides a function to verify a given password against the stored hash. Use crypto_pwhash_OPSLIMIT_SENSITIVE and crypto_pwhash_MEMLIMIT_SENSITIVE for sensitive data. ```c #define PASSWORD "Correct Horse Battery Staple" char hashed_password[crypto_pwhash_STRBYTES]; if (crypto_pwhash_str (hashed_password, PASSWORD, strlen(PASSWORD), crypto_pwhash_OPSLIMIT_SENSITIVE, crypto_pwhash_MEMLIMIT_SENSITIVE) != 0) { /* out of memory */ } if (crypto_pwhash_str_verify (hashed_password, PASSWORD, strlen(PASSWORD)) != 0) { /* wrong password */ } ``` -------------------------------- ### Secure Two-Party Computation with Ristretto255 Source: https://libsodium.gitbook.io/doc/advanced/point-arithmetic/ristretto Demonstrates a secure two-party computation protocol for f(x) = p(x)^k using Ristretto255. This example involves blinding inputs, scalar multiplication, and element addition for unblinding. ```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]; crypto_core_ristretto255_scalar_random(k); // Compute v = g^k unsigned char v[crypto_core_ristretto255_BYTES]; crypto_scalarmult_ristretto255_base(v, k); // Compute b = a^k unsigned char b[crypto_core_ristretto255_BYTES]; 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); ``` -------------------------------- ### HMAC-SHA-512 Multi-Part (Streaming) Example Source: https://libsodium.gitbook.io/doc/advanced/hmac-sha2 Shows how to compute an HMAC-SHA-512 hash for a message that is processed in multiple parts using a streaming API. This involves initialization, updating with message parts, and finalization. ```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); ``` -------------------------------- ### Sealed Box Encryption and Decryption Example Source: https://libsodium.gitbook.io/doc/public-key_cryptography/sealed_boxes Demonstrates the complete process of creating a sealed box: generating a recipient's key pair, encrypting a message anonymously using an ephemeral key pair and the recipient's public key, and then decrypting the message with the recipient's key pair. Ensure the recipient's public key is available for encryption and both public and private keys for decryption. ```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 */ } ``` -------------------------------- ### Main Function for Secretstream File Encryption/Decryption Source: https://libsodium.gitbook.io/doc/secret-key_cryptography/secretstream Initializes libsodium, generates a secret key, and then calls the encrypt and decrypt functions to process a sample file. This serves as a complete example of the secretstream workflow. ```c int main(void) { unsigned char key[crypto_secretstream_xchacha20poly1305_KEYBYTES]; if (sodium_init() != 0) { return 1; } crypto_secretstream_xchacha20poly1305_keygen(key); if (encrypt("/tmp/encrypted", "/tmp/original", key) != 0) { return 1; } if (decrypt("/tmp/decrypted", "/tmp/encrypted", key) != 0) { return 1; } return 0; } ``` -------------------------------- ### Secure Two-Party Computation Example Source: https://libsodium.gitbook.io/doc/advanced/point-arithmetic Demonstrates a secure two-party computation of f(x) = p(x)^k. 'x' is blinded by the first party, and 'k' is a secret key for the second party. 'p(x)' is a hash-to-curve function. ```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); ``` -------------------------------- ### Initialize Libsodium from a Library (Windows) Source: https://libsodium.gitbook.io/doc/quickstart Use `DllMain()` on Windows to call `sodium_init()` when a library is loaded. ```c /* Example for DllMain() on Windows */ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: if (sodium_init() < 0) { /* handle error */ } break; /* ... other cases ... */ } return TRUE; } ``` -------------------------------- ### Include Header and Initialize Library Source: https://libsodium.gitbook.io/doc/usage Include the `sodium.h` header and call `sodium_init()` before using any other libsodium functions. `sodium_init()` is safe to call multiple times and from different threads. ```c #include int main(void) { if (sodium_init() == -1) { return 1; } ... } ``` -------------------------------- ### Initialize Libsodium Library Source: https://libsodium.gitbook.io/doc/quickstart Call `sodium_init()` before using any other libsodium functions. It's safe to call multiple times. ```c #include int main(void) { if (sodium_init() < 0) { /* panic! the library couldn't be initialized; it is not safe to use */ } return 0; } ``` -------------------------------- ### Sponge Construction: Absorb Block Example Source: https://libsodium.gitbook.io/doc/advanced/keccak1600 Example function to absorb a single block of data into the Keccak-f[1600] state using a specified rate and applying the permutation. Use `permute_24` for SHAKE or `permute_12` for TurboSHAKE. ```c #define RATE 136 /* For a 256-bit capacity (like SHAKE256/TurboSHAKE256) */ void absorb_block(crypto_core_keccak1600_state *state, const unsigned char *block) { crypto_core_keccak1600_xor_bytes(state, block, 0, RATE); crypto_core_keccak1600_permute_24(state); /* or permute_12 for TurboSHAKE */ } ``` -------------------------------- ### Get a random 32-bit unsigned integer Source: https://libsodium.gitbook.io/doc/generating_random_data Returns an unpredictable value between 0 and 0xffffffff. Use this for general random number generation. ```c uint32_t randombytes_random(void); ``` -------------------------------- ### Multi-part (Streaming) Interface Source: https://libsodium.gitbook.io/doc/advanced/poly1305 Allows authentication of messages in chunks. Initialize the state, update with message parts, and finalize to get the authenticator. ```APIDOC ## crypto_onetimeauth_init ### Description Initializes a `crypto_onetimeauth_state` structure using the provided secret key. ### Function Signature ```c int crypto_onetimeauth_init(crypto_onetimeauth_state *state, const unsigned char *key); ``` ### Parameters - `state` (crypto_onetimeauth_state *): Pointer to the state structure to be initialized. Requires 16-byte alignment. - `key` (const unsigned char *): The secret key. ## crypto_onetimeauth_update ### Description Updates the authentication state with a chunk of the message. ### Function Signature ```c int crypto_onetimeauth_update(crypto_onetimeauth_state *state, const unsigned char *in, unsigned long long inlen); ``` ### Parameters - `state` (crypto_onetimeauth_state *): Pointer to the initialized state structure. - `in` (const unsigned char *): The message chunk to process. - `inlen` (unsigned long long): The length of the message chunk. ## crypto_onetimeauth_final ### Description Finalizes the multi-part authentication and puts the resulting authenticator into `out`. ### Function Signature ```c int crypto_onetimeauth_final(crypto_onetimeauth_state *state, unsigned char *out); ``` ### Parameters - `state` (crypto_onetimeauth_state *): Pointer to the state structure after all updates. - `out` (unsigned char *): Buffer to store the final authenticator (crypto_onetimeauth_BYTES). ``` -------------------------------- ### SHA-512 Multi-part API Source: https://libsodium.gitbook.io/doc/advanced/sha-2_hash_function Functions for multi-part SHA-512 hashing, including initialization, updating with data chunks, and finalization to get the hash. ```c int crypto_hash_sha512_init(crypto_hash_sha512_state *state); int crypto_hash_sha512_update(crypto_hash_sha512_state *state, const unsigned char *in, unsigned long long inlen); int crypto_hash_sha512_final(crypto_hash_sha512_state *state, unsigned char *out); ``` -------------------------------- ### Hashing with Domain Separation using TurboSHAKE128 Source: https://libsodium.gitbook.io/doc/hashing/xof Demonstrates using domain separators with crypto_xof_turboshake128_init_with_domain to create independent hash functions for different contexts. ```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); ``` -------------------------------- ### SHA-256 Multi-part API Source: https://libsodium.gitbook.io/doc/advanced/sha-2_hash_function Functions for multi-part SHA-256 hashing, including initialization, updating with data chunks, and finalization to get the hash. ```c int crypto_hash_sha256_init(crypto_hash_sha256_state *state); int crypto_hash_sha256_update(crypto_hash_sha256_state *state, const unsigned char *in, unsigned long long inlen); int crypto_hash_sha256_final(crypto_hash_sha256_state *state, unsigned char *out); ``` -------------------------------- ### Cross-compiling with Zig Source: https://libsodium.gitbook.io/doc/installation Cross-compile libsodium using Zig for various targets. Examples include AArch64 Windows, RISC-V Linux, and WebAssembly. ```shell $ zig build -Doptimize=ReleaseFast -Dtarget=aarch64-windows $ zig build -Doptimize=ReleaseFast -Dtarget=riscv64-linux $ zig build -Doptimize=ReleaseFast -Dtarget=wasm32-wasi ``` -------------------------------- ### Compiling with CompCert Source: https://libsodium.gitbook.io/doc/installation Compile libsodium using the CompCert compiler on a little-endian system. This command disables shared libraries and installs the compiled code. ```shell $ env CC=ccomp CFLAGS="-O2 -fstruct-passing" ./configure --disable-shared && \ make && sudo make install ``` -------------------------------- ### Single-part SHA3-512 Hashing Source: https://libsodium.gitbook.io/doc/advanced/sha-3_hash_function Example demonstrating how to compute a SHA3-512 hash for a message in a single operation. The output buffer size is determined by crypto_hash_sha3512_BYTES. ```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); ``` -------------------------------- ### Compiling with Zig (Size Optimized) Source: https://libsodium.gitbook.io/doc/installation Compile libsodium for the current target using Zig with release-small optimization for size-constrained environments. ```shell $ zig build -Doptimize=ReleaseSmall ``` -------------------------------- ### Get Keccak-f[1600] State Size Source: https://libsodium.gitbook.io/doc/advanced/keccak1600 Queries the size of the Keccak-f[1600] state structure at runtime. This function returns a constant value of 224. ```c size_t crypto_core_keccak1600_statebytes(void); ``` -------------------------------- ### Building XChaCha20 with HChaCha20 Source: https://libsodium.gitbook.io/doc/key_derivation Demonstrates how to use `crypto_core_hchacha20` to build XChaCha20, a variant of ChaCha20-Poly1305 that uses a 192-bit nonce. This snippet shows key and nonce generation, deriving the subkey using `crypto_core_hchacha20`, and then performing encryption. ```c #define MESSAGE (const unsigned char *) "message" #define MESSAGE_LEN 7 unsigned char c[crypto_aead_chacha20poly1305_ABYTES + MESSAGE_LEN]; unsigned char k[crypto_core_hchacha20_KEYBYTES]; unsigned char k2[crypto_core_hchacha20_OUTPUTBYTES]; unsigned char n[crypto_core_hchacha20_INPUTBYTES + crypto_aead_chacha20poly1305_NPUBBYTES]; randombytes_buf(k, sizeof k); randombytes_buf(n, sizeof n); /* 192-bits nonce */ crypto_core_hchacha20(k2, n, k, NULL); assert(crypto_aead_chacha20poly1305_KEYBYTES <= sizeof k2); assert(crypto_aead_chacha20poly1305_NPUBBYTES == (sizeof n) - crypto_core_hchacha20_INPUTBYTES); crypto_aead_chacha20poly1305_encrypt(c, NULL, MESSAGE, MESSAGE_LEN, NULL, 0, NULL, n + crypto_core_hchacha20_INPUTBYTES, k2); ``` -------------------------------- ### Cross-compiling to Apple Devices Source: https://libsodium.gitbook.io/doc/installation Use this script to create an xcframework package for Apple platforms. ```shell ./dist-build/apple-xcframework.sh ``` -------------------------------- ### Compiling with Zig (Current Target) Source: https://libsodium.gitbook.io/doc/installation Compile libsodium for the current target using Zig with release-fast optimization. ```shell $ zig build -Doptimize=ReleaseFast ``` -------------------------------- ### Initialize Libsodium from a Library (GCC/Clang) Source: https://libsodium.gitbook.io/doc/quickstart Use `__attribute__((constructor))` on GCC, Clang, or icc for macOS and ELF-based systems to call `sodium_init()` on library load. ```c /* Example for __attribute__((constructor)) on GCC/Clang/icc */ __attribute__((constructor)) void libsodium_init(void) { if (sodium_init() < 0) { /* handle error */ } } ``` -------------------------------- ### Keccak-f[1600] Sponge Construction Usage Source: https://libsodium.gitbook.io/doc/advanced/keccak1600 Demonstrates the typical usage pattern for the Keccak-f[1600] permutation following the sponge construction: initialize, absorb data, and squeeze output. This is a low-level API and requires manual permutation calls. ```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); ``` -------------------------------- ### SHAKE256 Initialize with Custom Domain Source: https://libsodium.gitbook.io/doc/hashing/xof Initializes the SHAKE256 state with a custom domain separator. This allows different applications to use the same XOF without risk of collisions by producing unrelated outputs. ```c int crypto_xof_shake256_init_with_domain(crypto_xof_shake256_state *state, unsigned char domain); ```