The php Function sodium_hex2bin()
The php function sodium_hex2bin() parses a hexadecimally encoded string into a binary string. It takes a base64 variant and an optional set of characters to ignore (typically whitespaces and newlines) as input and returns the binary representation of the resulting string data. The function evaluates in constant time for a given length and format.
libsodium is a library that provides modern cryptographic primitives for PHP developers to safely implement encryption and decryption. PHP 7.2 and later ships with it as a core extension and it can also be installed as a PECL Extension for older versions of the language.
There are many different cryptographic algorithms available in libsodium, but the most important ones are Curve25519 and AES-GCM. These are strong cryptographic algorithms that resist side-channel attacks such as GPU cracking, so they provide a high level of security when implemented correctly.
In addition to the above functions, libsodium also contains other useful functions like sodium_crypto_pwhash() that derives a strong secret key from a password using a hash function and salt, and sodium_crypto_kx_seed_keypair() that generates a deterministic public/private key pair from a seed. Using these functions, it is easy to create secure remote password-exchange protocols that are resistant to side-channel attacks.
As a final note, always store passwords safely by never encrypting them – use a hash instead! A hash can be stored in a database and is much less vulnerable to side-channel attacks. For more information on how to securely store passwords in your application, check out this ZendCon and OpenEnterprise presentation from Perforce by Mike O'Neil.