Sodium Cryptography in PHP 8.1
A php function is a set of instructions that will be executed when the code is called. Unlike variables with local scope, functions can be used from multiple functions in a PHP script. The main part of a php function is the return statement, which is responsible for putting the final output of the function into the variable that was passed into it.
In PHP 7, the php team introduced Type Declarations for function arguments, which allows you to declare what the parameters of a function should have as types. This will prevent you from passing in values of a different type than what the function expects. PHP 8.1 takes this a step further by adding support for a new return type that you can use in your functions. This will make the function throw a fatal error if it doesn’t return the correct type. To enable this feature, add a return type to the function by placing it before the open curly bracket of the function declaration.
Another new addition to the PHP API is fdatasync(), which works like fflush() but doesn’t include metadata when flushing the buffer to physical storage. This is useful when you only need to synchronize data but not metadata.
Sodium is a modern, easy-to-use cryptographic library that can be used for encryption, decryption, password hashing, and signatures. The PECL libsodium extension provides a wrapper for it in PHP, and it’s used by leading technology companies such as Facebook, Discord, Malwarebytes, and Valve. In PHP 8.1, three new functions provide direct XChaCha20 stream encryption functionality without authentication, known as detached mode. The sodium_crypto_stream_xchacha20_keygen function returns a secure random key, and the sodium_crypto_stream_xchacha20_xor and sodium_crypto_stream_xchacha20_poly1305_ietf_encrypt / decrypt functions expand the key and nonce into a stream of pseudorandom bytes.