global $CTX; $key = sodium_crypto_secretbox_keygen(); $hex_key = sodium_bin2hex($key); $CTX->set("", $hex_key, ""); global $CTX; $message = ""; $key = sodium_hex2bin(K_ENCRYPTION_KEY); $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); $ciphertext = sodium_crypto_secretbox($message, $nonce, $key); $encrypted = base64_encode($nonce . $ciphertext); $CTX->set("", $encrypted, ""); global $CTX; $key = sodium_hex2bin(K_ENCRYPTION_KEY); $nonceFromEncrypted = mb_substr(base64_decode(""), 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit'); $ciphertextFromEncrypted = mb_substr(base64_decode(""), SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit'); $decrypted = sodium_crypto_secretbox_open($ciphertextFromEncrypted, $nonceFromEncrypted, $key); if ($decrypted === false) { throw new Exception('The message was tampered with in transit'); } $CTX->set("", $decrypted, "");