If you’ve worked with PHP with any length of time and needed to use some type of built-in encryption, you’ve likely seen something about the Sodium library in the manual.

Sodium is a modern, easy-to-use software library for encryption, decryption, signatures, password hashing and more. Its goal is to provide all of the core operations needed to build higher-level cryptographic tools.

Unfortunately, the module that contains this library isn’t always installed with the PHP binary. It then has to be either re-compiled or enabled by a package manager. If you don’t have the ability, time, or access to do any of those, then there’s a solid alternative for the native library that can be installed via Composer: Sodium Compat.

Sodium Compat

Sodium Compat is a pure PHP polyfill for the Sodium cryptography library (libsodium), a core extension in PHP 7.2.0+ and otherwise available in PECL.

This library tentatively supports PHP 5.2.4 – 8.x (latest), but officially only supports non-EOL’d versions of PHP.

If you have the PHP extension installed, Sodium Compat will opportunistically and transparently use the PHP extension instead of our implementation.

Once you install Sodium Compat via Composer, you can use all of the functions that are available in Sodium via the PHP manual without having to do anything else.

Two things to note about the project, though (both of which are available on the project page):

  1. “This cryptography library has not been formally audited by an independent third party that specializes in cryptography or cryptanalysis.”
  2. “sodium_compat was developed by Paragon Initiative Enterprises, a company that specializes in secure PHP development and PHP cryptography, and has been informally reviewed by many other security experts who also specialize in PHP.”

All that to say that if you install Sodium Compat via Composer, you’re going to get almost identical to the Sodium library that ships with PHP without the need need to work with your host, compiled binary, or the available libraries.

And, for what it’s worth, I’ve used this in a couple of projects now and have had success with it.