### Key Management from Raw Bytes Source: https://context7.com/terl/lazysodium-android/llms.txt Instantiate a `Key` object directly from raw byte arrays, which is useful when keys are generated or retrieved in byte format. ```java // Create key from raw bytes Key rawKey = Key.fromBytes(randomBytes); ``` -------------------------------- ### Execute BLAKE2b Generic Hashing Source: https://context7.com/terl/lazysodium-android/llms.txt Covers simple hashing, keyed hashing, and multi-part streaming hashing for large data sets. ```java import com.goterl.lazysodium.interfaces.GenericHash; import com.goterl.lazysodium.utils.Key; import com.goterl.lazysodium.exceptions.SodiumException; // Generate a hash key (optional for keyed hashing) Key key = lazySodium.cryptoGenericHashKeygen(); // Simple hash without key String message = "https://terl.co"; String hash = lazySodium.cryptoGenericHash(message); // Keyed hash with custom key size Key customKey = lazySodium.cryptoGenericHashKeygen(GenericHash.KEYBYTES_MAX); // Multi-part hashing for large data or streaming String part1 = "The sun"; String part2 = "is shining"; String part3 = "brightly today"; byte[] state = new byte[lazySodium.cryptoGenericHashStateBytes()]; lazySodium.cryptoGenericHashInit(state, key, GenericHash.BYTES); lazySodium.cryptoGenericHashUpdate(state, part1); lazySodium.cryptoGenericHashUpdate(state, part2); lazySodium.cryptoGenericHashUpdate(state, part3); String finalHash = lazySodium.cryptoGenericHashFinal(state, GenericHash.BYTES); ``` -------------------------------- ### Key Management from Hex and Plain Strings Source: https://context7.com/terl/lazysodium-android/llms.txt Create `Key` objects from hexadecimal strings or plain strings. Note that creating keys from plain strings is not recommended for production environments due to security implications. ```java // Convert hex string to bytes via Key Key key = Key.fromHexString("0ae5c84877c9c534ffbb1f854550895a25a9ded6bd6b8a9035f38b9e03a0dfe2"); byte[] keyBytes = key.getAsBytes(); String keyHex = key.getAsHexString(); ``` ```java // Create key from plain string (not recommended for production) Key plainKey = Key.fromPlainString("my_32_byte_key_here_1234567890!"); ``` -------------------------------- ### Establish session keys with KeyExchange Source: https://context7.com/terl/lazysodium-android/llms.txt Perform X25519-based key exchange to generate shared session keys between client and server. Supports deterministic keypair generation from a seed. ```java import com.goterl.lazysodium.interfaces.KeyExchange; import com.goterl.lazysodium.utils.KeyPair; import com.goterl.lazysodium.utils.SessionPair; import com.goterl.lazysodium.exceptions.SodiumException; // Generate keypairs for client and server KeyPair clientKeys = lazySodium.cryptoKxKeypair(); KeyPair serverKeys = lazySodium.cryptoKxKeypair(); // Client computes session keys SessionPair clientSession = lazySodium.cryptoKxClientSessionKeys(clientKeys, serverKeys); // Server computes session keys SessionPair serverSession = lazySodium.cryptoKxServerSessionKeys(serverKeys, clientKeys); // Client's Rx key equals Server's Tx key (for receiving client messages) // Client's Tx key equals Server's Rx key (for sending to client) String clientRxKey = clientSession.getRxString(); String serverTxKey = serverSession.getTxString(); // clientRxKey.equals(serverTxKey) == true // Use session keys for encrypted communication // Client sends using Tx key, Server receives using Rx key // Generate deterministic keypair from seed byte[] seed = new byte[KeyExchange.SEEDBYTES]; KeyPair deterministicKeys = lazySodium.cryptoKxKeypair(seed); ``` -------------------------------- ### Derive subkeys with KeyDerivation Source: https://context7.com/terl/lazysodium-android/llms.txt Derive multiple subkeys from a single master key using either Native or Lazy interfaces. Context strings must be 8 bytes or less. ```java import com.goterl.lazysodium.interfaces.KeyDerivation; import com.goterl.lazysodium.utils.Key; import com.goterl.lazysodium.exceptions.SodiumException; KeyDerivation.Native kdfNative = (KeyDerivation.Native) lazySodium; KeyDerivation.Lazy kdfLazy = (KeyDerivation.Lazy) lazySodium; // Generate a master key byte[] masterKey = new byte[KeyDerivation.MASTER_KEY_BYTES]; kdfNative.cryptoKdfKeygen(masterKey); // Context string (8 bytes max, describes purpose) String context = "Examples"; byte[] contextBytes = lazySodium.bytes(context); // Derive subkey using Native interface byte[] subKey1 = new byte[KeyDerivation.BYTES_MAX]; kdfNative.cryptoKdfDeriveFromKey( subKey1, subKey1.length, 1L, // Subkey ID contextBytes, masterKey ); // Derive subkey using Lazy interface Key subKey2 = kdfLazy.cryptoKdfDeriveFromKey( KeyDerivation.BYTES_MAX, // Output length 2L, // Different subkey ID context, Key.fromBytes(masterKey) ); // Derive encryption key and auth key from same master Key encryptionKey = kdfLazy.cryptoKdfDeriveFromKey(32, 1L, "encrypt!", Key.fromBytes(masterKey)); Key authKey = kdfLazy.cryptoKdfDeriveFromKey(32, 2L, "auth!!!!", Key.fromBytes(masterKey)); ``` -------------------------------- ### Implement Argon2 Password Hashing Source: https://context7.com/terl/lazysodium-android/llms.txt Provides methods for secure password storage, verification, and key derivation using the Argon2 algorithm. ```java import com.goterl.lazysodium.interfaces.PwHash; import com.goterl.lazysodium.exceptions.SodiumException; import com.sun.jna.NativeLong; PwHash.Lazy pwHash = (PwHash.Lazy) lazySodium; String password = "Password123456!!!!@@"; // Hash password for storage (returns ASCII-encoded hash string) String hashedPassword = pwHash.cryptoPwHashStr( password, PwHash.OPSLIMIT_INTERACTIVE, // CPU operations limit PwHash.MEMLIMIT_INTERACTIVE // Memory limit in bytes ); // Verify password against stored hash boolean isCorrect = pwHash.cryptoPwHashStrVerify(hashedPassword, password); // Result: true // Derive encryption key from password byte[] salt = lazySodium.randomBytesBuf(PwHash.SALTBYTES); String derivedKey = pwHash.cryptoPwHash( password, PwHash.BYTES_MIN, // Output key length salt, 5L, // Operations limit new NativeLong(8192 * 2), // Memory limit PwHash.Alg.PWHASH_ALG_ARGON2ID13 // Algorithm ); // Hash with null bytes removed (useful for display) String cleanHash = pwHash.cryptoPwHashStrRemoveNulls( password, PwHash.OPSLIMIT_MIN, PwHash.MEMLIMIT_MIN ); ``` -------------------------------- ### Symmetric Encryption (SecretBox) Source: https://context7.com/terl/lazysodium-android/llms.txt Perform authenticated symmetric encryption using SecretBox with XSalsa20 and Poly1305. Requires generating a key and a unique nonce for each message. Supports encryption and decryption of string messages. ```java import com.goterl.lazysodium.interfaces.SecretBox; import com.goterl.lazysodium.utils.Key; import com.goterl.lazysodium.exceptions.SodiumException; SecretBox.Lazy secretBox = (SecretBox.Lazy) lazySodium; // Generate a random symmetric key Key key = secretBox.cryptoSecretBoxKeygen(); // Generate a random nonce (must be unique for each message) byte[] nonce = lazySodium.nonce(SecretBox.NONCEBYTES); // Encrypt a message String message = "This is a super secret message."; String ciphertext = secretBox.cryptoSecretBoxEasy(message, nonce, key); // Decrypt the message String decrypted = secretBox.cryptoSecretBoxOpenEasy(ciphertext, nonce, key); // Result: "This is a super secret message." // Use existing key from hex string Key existingKey = Key.fromHexString("your_64_char_hex_key_here"); String encrypted = secretBox.cryptoSecretBoxEasy(message, nonce, existingKey); ``` -------------------------------- ### Stream Cipher Encryption and Decryption Source: https://context7.com/terl/lazysodium-android/llms.txt Demonstrates XOR-based symmetric stream encryption and decryption using ChaCha20, ChaCha20-IETF, Salsa20, and XSalsa20. Ensure correct nonce sizes and key generation for each method. ```java import com.goterl.lazysodium.interfaces.Stream; import com.goterl.lazysodium.utils.Key; Stream.Lazy streamLazy = (Stream.Lazy) lazySodium; String message = "A top secret message."; // ChaCha20 byte[] chachaNonce = lazySodium.nonce(Stream.CHACHA20_NONCEBYTES); Key chachaKey = streamLazy.cryptoStreamKeygen(Stream.Method.CHACHA20); String chachaCipher = streamLazy.cryptoStreamXor(message, chachaNonce, chachaKey, Stream.Method.CHACHA20); String chachaDecrypted = streamLazy.cryptoStreamXorDecrypt(chachaCipher, chachaNonce, chachaKey, Stream.Method.CHACHA20); // ChaCha20-IETF (96-bit nonce) byte[] ietfNonce = lazySodium.nonce(Stream.CHACHA20_IETF_NONCEBYTES); Key ietfKey = streamLazy.cryptoStreamKeygen(Stream.Method.CHACHA20_IETF); String ietfCipher = streamLazy.cryptoStreamXor(message, ietfNonce, ietfKey, Stream.Method.CHACHA20_IETF); String ietfDecrypted = streamLazy.cryptoStreamXorDecrypt(ietfCipher, ietfNonce, ietfKey, Stream.Method.CHACHA20_IETF); // Salsa20 byte[] salsaNonce = lazySodium.nonce(Stream.SALSA20_NONCEBYTES); Key salsaKey = streamLazy.cryptoStreamKeygen(Stream.Method.SALSA20); String salsaCipher = streamLazy.cryptoStreamXor(message, salsaNonce, salsaKey, Stream.Method.SALSA20); String salsaDecrypted = streamLazy.cryptoStreamXorDecrypt(salsaCipher, salsaNonce, salsaKey, Stream.Method.SALSA20); // XSalsa20 (192-bit nonce) byte[] xsalsaNonce = lazySodium.nonce(Stream.XSALSA20_NONCEBYTES); Key xsalsaKey = streamLazy.cryptoStreamKeygen(Stream.Method.XSALSA20); String xsalsaCipher = streamLazy.cryptoStreamXor(message, xsalsaNonce, xsalsaKey, Stream.Method.XSALSA20); String xsalsaDecrypted = streamLazy.cryptoStreamXorDecrypt(xsalsaCipher, xsalsaNonce, xsalsaKey, Stream.Method.XSALSA20); ``` -------------------------------- ### Generate Random Bytes and Nonce Source: https://context7.com/terl/lazysodium-android/llms.txt Use `randomBytesBuf` to generate cryptographically secure random bytes and `nonce` for generating initialization vectors or nonces of a specified size. ```java // Generate random bytes byte[] randomBytes = lazySodium.randomBytesBuf(32); ``` ```java // Generate nonce of specific size byte[] nonce = lazySodium.nonce(24); ``` -------------------------------- ### Perform Ed25519 Digital Signatures Source: https://context7.com/terl/lazysodium-android/llms.txt Demonstrates keypair generation, message signing, verification, and key conversion for Ed25519 signatures. ```java import com.goterl.lazysodium.interfaces.Sign; import com.goterl.lazysodium.utils.KeyPair; import com.goterl.lazysodium.exceptions.SodiumException; Sign.Lazy cryptoSign = (Sign.Lazy) lazySodium; // Generate a signing keypair KeyPair keyPair = cryptoSign.cryptoSignKeypair(); // Sign a message (signature prepended to message) String message = "This should get signed"; String signedMessage = cryptoSign.cryptoSign(message, keyPair.getSecretKey().getAsHexString()); // Verify and extract original message String originalMessage = cryptoSign.cryptoSignOpen(signedMessage, keyPair.getPublicKey()); // Result: "This should get signed" // Detached signature (signature separate from message) String signature = lazySodium.cryptoSignDetached(message, keyPair.getSecretKey()); boolean isValid = lazySodium.cryptoSignVerifyDetached(signature, message, keyPair.getPublicKey()); // Result: true // Generate deterministic keypair from seed byte[] seed = new byte[Sign.SEEDBYTES]; KeyPair deterministicKeys = cryptoSign.cryptoSignSeedKeypair(seed); // Convert Ed25519 keys to Curve25519 for Box encryption KeyPair curve25519KeyPair = lazySodium.convertKeyPairEd25519ToCurve25519(keyPair); // Extract keypair from secret key KeyPair extractedKeys = lazySodium.cryptoSignSecretKeyPair(keyPair.getSecretKey()); ``` -------------------------------- ### String and Byte Array Conversions Source: https://context7.com/terl/lazysodium-android/llms.txt Convert strings to byte arrays using `bytes()` and byte arrays back to strings using `str()`. For hexadecimal representations, use `toHexStr()`. ```java // Convert string to bytes byte[] bytes = lazySodium.bytes("Hello"); ``` ```java // Convert bytes to string String str = lazySodium.str(bytes); ``` ```java // Convert bytes to hex string String hexString = lazySodium.toHexStr(randomBytes); ``` -------------------------------- ### Initialize LazySodiumAndroid Source: https://context7.com/terl/lazysodium-android/llms.txt Initialize LazySodiumAndroid for cryptographic operations. Supports default UTF-8 charset and hex encoding, or custom charset. Access the underlying Sodium instance for native operations. ```java import com.goterl.lazysodium.LazySodiumAndroid; import com.goterl.lazysodium.SodiumAndroid; // Basic initialization with UTF-8 charset and hex encoding LazySodiumAndroid lazySodium = new LazySodiumAndroid(new SodiumAndroid()); // Custom initialization with specific charset LazySodiumAndroid lazySodium = new LazySodiumAndroid( new SodiumAndroid(), StandardCharsets.UTF_8 ); // Access the underlying Sodium instance for native operations SodiumAndroid sodium = lazySodium.getSodium(); ``` -------------------------------- ### SHA-256 and SHA-512 Hashing Source: https://context7.com/terl/lazysodium-android/llms.txt Use for single-pass or multi-part hashing with SHA-256 and SHA-512. Ensure proper initialization, updates, and finalization for multi-part hashing. ```java import com.goterl.lazysodium.interfaces.Hash; import com.goterl.lazysodium.exceptions.SodiumException; String message = "With great power comes great responsibility"; // Single-pass SHA-256 String sha256Hash = lazySodium.cryptoHashSha256(message); // Single-pass SHA-512 String sha512Hash = lazySodium.cryptoHashSha512(message); // Multi-part SHA-256 for streaming data Hash.State256 state256 = new Hash.State256.ByReference(); lazySodium.cryptoHashSha256Init(state256); lazySodium.cryptoHashSha256Update(state256, "With great power "); lazySodium.cryptoHashSha256Update(state256, "comes great responsibility"); lazySodium.cryptoHashSha256Update(state256, " - additional data"); String streamingHash256 = lazySodium.cryptoHashSha256Final(state256); // Multi-part SHA-512 for streaming data Hash.State512 state512 = new Hash.State512.ByReference(); lazySodium.cryptoHashSha512Init(state512); lazySodium.cryptoHashSha512Update(state512, "Part 1"); lazySodium.cryptoHashSha512Update(state512, "Part 2"); String streamingHash512 = lazySodium.cryptoHashSha512Final(state512); ``` -------------------------------- ### AEAD Encryption with AES-256-GCM Source: https://context7.com/terl/lazysodium-android/llms.txt Utilizes hardware acceleration if available for AES-256-GCM encryption. Requires a key and nonce, and supports optional associated data. ```java import com.goterl.lazysodium.interfaces.AEAD; import com.goterl.lazysodium.utils.Key; String plaintext = "superSecurePassword"; // AES-256-GCM (hardware accelerated when available) if (lazySodium.cryptoAeadAES256GCMIsAvailable()) { Key aesKey = lazySodium.keygen(AEAD.Method.AES256GCM); byte[] aesNonce = lazySodium.nonce(AEAD.AES256GCM_NPUBBYTES); String aesCipher = lazySodium.encrypt(plaintext, null, aesNonce, aesKey, AEAD.Method.AES256GCM); String aesDecrypted = lazySodium.decrypt(aesCipher, null, aesNonce, aesKey, AEAD.Method.AES256GCM); } ``` -------------------------------- ### AEAD Encryption with XChaCha20-Poly1305-IETF Source: https://context7.com/terl/lazysodium-android/llms.txt Recommended for most AEAD encryption uses. Generates a key and nonce, then encrypts and decrypts plaintext with optional associated data. ```java import com.goterl.lazysodium.interfaces.AEAD; import com.goterl.lazysodium.utils.Key; import com.goterl.lazysodium.utils.DetachedEncrypt; import com.goterl.lazysodium.utils.DetachedDecrypt; import javax.crypto.AEADBadTagException; String plaintext = "superSecurePassword"; String additionalData = null; // Optional associated data // XChaCha20-Poly1305-IETF (recommended for most uses) Key xchachaKey = lazySodium.keygen(AEAD.Method.XCHACHA20_POLY1305_IETF); byte[] xchachaNonce = lazySodium.nonce(AEAD.XCHACHA20POLY1305_IETF_NPUBBYTES); String xchachaCipher = lazySodium.encrypt(plaintext, additionalData, xchachaNonce, xchachaKey, AEAD.Method.XCHACHA20_POLY1305_IETF); String xchachaDecrypted = lazySodium.decrypt(xchachaCipher, additionalData, xchachaNonce, xchachaKey, AEAD.Method.XCHACHA20_POLY1305_IETF); ``` -------------------------------- ### Diffie-Hellman Key Agreement and Encryption Source: https://context7.com/terl/lazysodium-android/llms.txt Implements Diffie-Hellman key exchange using Curve25519 to establish a shared secret, followed by symmetric encryption/decryption using SecretBox. Requires generating key pairs on both client and server sides. ```java import com.goterl.lazysodium.interfaces.DiffieHellman; import com.goterl.lazysodium.interfaces.SecretBox; import com.goterl.lazysodium.interfaces.Box; import com.goterl.lazysodium.utils.Key; import com.goterl.lazysodium.exceptions.SodiumException; DiffieHellman.Lazy dh = (DiffieHellman.Lazy) lazySodium; SecretBox.Lazy secretBox = (SecretBox.Lazy) lazySodium; // Client generates keypair Key clientSecretKey = Key.fromPlainString("CLIENT_TOP_SECRET_KEY_1234567890"); Key clientPublicKey = dh.cryptoScalarMultBase(clientSecretKey); // Server generates keypair Key serverSecretKey = Key.fromPlainString("SERVER_TOP_SECRET_KEY_1234567890"); Key serverPublicKey = dh.cryptoScalarMultBase(serverSecretKey); // --- ON THE CLIENT --- // Compute shared key (client secret + server public) Key clientSharedKey = dh.cryptoScalarMult(clientSecretKey, serverPublicKey); // Encrypt message using shared key String message = "Hello Server!"; byte[] nonce = new byte[Box.NONCEBYTES]; String encrypted = secretBox.cryptoSecretBoxEasy(message, nonce, clientSharedKey); // --- ON THE SERVER --- // Compute same shared key (server secret + client public) Key serverSharedKey = dh.cryptoScalarMult(serverSecretKey, clientPublicKey); // Decrypt message using shared key String decrypted = secretBox.cryptoSecretBoxOpenEasy(encrypted, nonce, serverSharedKey); // Result: "Hello Server!" ``` -------------------------------- ### Secure Memory Operations Source: https://context7.com/terl/lazysodium-android/llms.txt Provides functions for securely managing memory, including zeroing sensitive data, locking memory to prevent swapping, and secure allocation using guarded pages. Also includes a constant-time comparison function. ```java import com.sun.jna.Pointer; // Zero out sensitive memory byte[] sensitiveData = new byte[] { 4, 2, 2, 1 }; boolean zeroed = lazySodium.sodiumMemZero(sensitiveData, sensitiveData.length); // sensitiveData is now all zeros // Lock memory to prevent paging to disk byte[] lockedData = new byte[] { 4, 5, 2, 1 }; boolean locked = lazySodium.sodiumMLock(lockedData, lockedData.length); // ... use locked data ... boolean unlocked = lazySodium.sodiumMUnlock(lockedData, lockedData.length); // Memory is zeroed on unlock // Secure memory allocation (guarded pages) int size = 10; Pointer securePtr = lazySodium.sodiumMalloc(size); byte[] secureData = securePtr.getByteArray(0, size); // ... use secure memory ... lazysodium.sodiumFree(securePtr); // Compare byte arrays in constant time (timing-safe) byte[] a = new byte[] { 4, 2, 2, 1 }; byte[] b = new byte[] { 4, 2, 2, 1 }; int result = lazySodium.getSodium().sodium_compare(a, b, 4); // Result: 0 (equal) ``` -------------------------------- ### AEAD Encryption with ChaCha20-Poly1305-IETF Source: https://context7.com/terl/lazysodium-android/llms.txt Encrypts and decrypts data using the ChaCha20-Poly1305-IETF algorithm. Requires a key and nonce, and supports optional associated data. ```java import com.goterl.lazysodium.interfaces.AEAD; import com.goterl.lazysodium.utils.Key; String plaintext = "superSecurePassword"; // ChaCha20-Poly1305-IETF Key chachaIetfKey = lazySodium.keygen(AEAD.Method.CHACHA20_POLY1305_IETF); byte[] chachaIetfNonce = lazySodium.nonce(AEAD.CHACHA20POLY1305_IETF_NPUBBYTES); String chachaIetfCipher = lazySodium.encrypt(plaintext, null, chachaIetfNonce, chachaIetfKey, AEAD.Method.CHACHA20_POLY1305_IETF); String chachaIetfDecrypted = lazySodium.decrypt(chachaIetfCipher, null, chachaIetfNonce, chachaIetfKey, AEAD.Method.CHACHA20_POLY1305_IETF); ``` -------------------------------- ### Asymmetric Encryption (Box) Source: https://context7.com/terl/lazysodium-android/llms.txt Perform public-key authenticated encryption using Box with Curve25519, XSalsa20, and Poly1305. Generate keypairs for encryption and decryption. Supports encrypting messages to a recipient using their public key and the sender's secret key. ```java import com.goterl.lazysodium.interfaces.Box; import com.goterl.lazysodium.utils.KeyPair; import com.goterl.lazysodium.exceptions.SodiumException; Box.Lazy cryptoBox = (Box.Lazy) lazySodium; // Generate keypairs for client and server KeyPair clientKeys = cryptoBox.cryptoBoxKeypair(); KeyPair serverKeys = cryptoBox.cryptoBoxKeypair(); // Client encrypts message to server String message = "Hello from client"; byte[] nonce = lazySodium.nonce(Box.NONCEBYTES); KeyPair encryptionKeyPair = new KeyPair(serverKeys.getPublicKey(), clientKeys.getSecretKey()); String encrypted = cryptoBox.cryptoBoxEasy(message, nonce, encryptionKeyPair); // Server decrypts message from client KeyPair decryptionKeyPair = new KeyPair(clientKeys.getPublicKey(), serverKeys.getSecretKey()); String decrypted = cryptoBox.cryptoBoxOpenEasy(encrypted, nonce, decryptionKeyPair); // Result: "Hello from client" // Generate deterministic keypair from seed byte[] seed = new byte[Box.SEEDBYTES]; KeyPair deterministicKeys = cryptoBox.cryptoBoxSeedKeypair(seed); // Pre-compute shared key for multiple messages (BeforeNm) String sharedKey = cryptoBox.cryptoBoxBeforeNm(encryptionKeyPair); String cipher = cryptoBox.cryptoBoxEasyAfterNm(message, nonce, sharedKey); String decryptedMsg = cryptoBox.cryptoBoxOpenEasyAfterNm(cipher, nonce, sharedKey); ``` -------------------------------- ### Add Lazysodium Android Dependency with Gradle Source: https://github.com/terl/lazysodium-android/blob/master/README.md Include the Lazysodium Android library and its JNA dependency in your project's build files. Ensure mavenCentral() is added to your repositories. Replace VERSION_NUMBER with the latest version. ```groovy repositories { // Add this to the end of any existing repositories mavenCentral() } // Project level dependencies section dependencies { implementation "com.goterl:lazysodium-android:VERSION_NUMBER@aar" implementation "net.java.dev.jna:jna:5.17.0@aar" } ``` -------------------------------- ### Stream encrypted messages with SecretStream Source: https://context7.com/terl/lazysodium-android/llms.txt Encrypt and decrypt sequential messages with ordering guarantees. Use tags to identify the final message in the stream. ```java import com.goterl.lazysodium.interfaces.SecretStream; import com.goterl.lazysodium.utils.Key; import com.goterl.lazysodium.exceptions.SodiumException; // Generate encryption key Key key = lazySodium.cryptoSecretStreamKeygen(); // Initialize encryption with random header byte[] header = lazySodium.randomBytesBuf(SecretStream.HEADERBYTES); SecretStream.State encryptState = lazySodium.cryptoSecretStreamInitPush(header, key); // Encrypt a sequence of messages String c1 = lazySodium.cryptoSecretStreamPush(encryptState, "First message", SecretStream.TAG_MESSAGE); String c2 = lazySodium.cryptoSecretStreamPush(encryptState, "Second message", SecretStream.TAG_MESSAGE); String c3 = lazySodium.cryptoSecretStreamPush(encryptState, "Final message", SecretStream.TAG_FINAL); // Initialize decryption with same header and key SecretStream.State decryptState = lazySodium.cryptoSecretStreamInitPull(header, key); // Decrypt messages in order byte[] tag = new byte[1]; String m1 = lazySodium.cryptoSecretStreamPull(decryptState, c1, tag); String m2 = lazySodium.cryptoSecretStreamPull(decryptState, c2, tag); String m3 = lazySodium.cryptoSecretStreamPull(decryptState, c3, tag); // Check if final message was received if (tag[0] == SecretStream.XCHACHA20POLY1305_TAG_FINAL) { // Stream complete } ``` -------------------------------- ### Detached AEAD Encryption/Decryption Source: https://context7.com/terl/lazysodium-android/llms.txt Performs AEAD encryption and decryption in detached mode, separating the ciphertext and authentication tag. Useful for specific integration scenarios. ```java import com.goterl.lazysodium.interfaces.AEAD; import com.goterl.lazysodium.utils.Key; import com.goterl.lazysodium.utils.DetachedEncrypt; import com.goterl.lazysodium.utils.DetachedDecrypt; String plaintext = "superSecurePassword"; String additionalData = null; // Detached mode (separate ciphertext and authentication tag) DetachedEncrypt encResult = lazySodium.encryptDetached(plaintext, null, null, null, null, AEAD.Method.XCHACHA20_POLY1305_IETF); DetachedDecrypt decResult = lazySodium.decryptDetached(encResult, null, null, null, null, AEAD.Method.XCHACHA20_POLY1305_IETF); String decryptedMessage = decResult.getMessageString(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.