Pure PHP polyfill for ext/sodium
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.
If you have the PHP extension installed, Sodium Compat will opportunistically and transparently use the PHP extension instead of our implementation.
Major Versions and Branches
sodium_compat v1.21.0 was the last v1.x release from the master branch. From now on, all future releases that support PHP 5.2 - 8.0 and 32-bit integers will be in the v1.x branch.
Newer versions of sodium_compat (i.e., v2.0.0) will continue to live in the master branch, unless a new major version is needed. The goal of this work is to improve code readability and performance, while reducing boilerplate code.
When in doubt, refer to the README file in the master branch for the latest in version information.
Which version should I use?
| sodium_compat version | PHP versions supported | 32-bit support? | Branch | |-----------------------|------------------------|-----------------|---------------------------------------------------------------| | v1.x.y | 5.2.4 - LATEST | YES | v1.x | | v2.x.y | 8.1 - LATEST | NO | master |
If you need 32-bit PHP support (PHPINTSIZE == 4), continue using sodium_compat v1.x. If you want improved performance and smaller dependencies, use v2.x.
We recommend libraries and frameworks set a Composer version constraint as follows:
{
"require": {
/ ... /
"paragonie/sodium_compat": ">= 1"
/ ... /
}
}
Applications should, conversely, specify the actual version that matters to them and their deployments.
IMPORTANT!
This cryptography library has not been formally audited by an independent third party that specializes in cryptography or cryptanalysis.
If you require such an audit before you can use sodium_compat in your projects and have the funds for such an audit, please open an issue or contact security at paragonie dot com so we can help get the ball rolling.
However, sodium_compat has been adopted by high profile open source projects, such as Joomla! and Magento. Furthermore, 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.
If you'd like to learn more about the defensive security measures we've taken to prevent sodium_compat from being a source of vulnerability in your systems, please read Cryptographically Secure PHP Development.
Installing Sodium Compat
If you're using Composer:
composer require paragonie/sodium_compat
Install From Source
If you're not using Composer, download a release tarball (which should be signed with our GnuPG public key), extract its contents, then include our autoload.php script in your project.
<?php
requireonce "/path/to/sodiumcompat/autoload.php";
PHP Archives (Phar) Releases
Since version 1.3.0, sodium_compat releases include a PHP Archive (.phar file) and associated GPG signature. First, download both files and verify them with our GPG public key, like so:
# Getting our public key from the keyserver:
gpg --fingerprint 7F52D5C61D1255C731362E826B97A1C2826404DA
if [ $? -ne 0 ]; then
echo -e "\033[33mDownloading PGP Public Key...\033[0m"
gpg --keyserver pgp.mit.edu --recv-keys 7F52D5C61D1255C731362E826B97A1C2826404DA
# Security <security@paragonie.com>
gpg --fingerprint 7F52D5C61D1255C731362E826B97A1C2826404DA
if [ $? -ne 0 ]; then
echo -e "\03331mCould not download PGP public key for verification\033[0m"
exit 1
fi
fi
Verifying the PHP Archive
gpg --verify sodium-compat.phar.sig sodium-compat.phar
Now, simply include this .phar file in your application.
<?php
require_once "/path/to/sodium-compat.phar";
Support
[Commercial support for libsodium is available from multiple vendors. If you need help using sodiumcompat in one of your projects, contact Paragon Initiative Enterprises.
Non-commercial report will be facilitated through Github issues. We offer no guarantees of our availability to resolve questions about integrating sodium_compat into third-party software for free, but will strive to fix any bugs (security-related or otherwise) in our library.
Support Contracts
If your company uses this library in their products or services, you may be interested in purchasing a support contract from Paragon Initiative Enterprises.
Using Sodium Compat
True Polyfill
As per the second vote on the libsodium RFC, PHP 7.2 uses sodium_ instead of \Sodium\.
<?php
requireonce "/path/to/sodiumcompat/autoload.php";
$alicekp = sodiumcryptosignkeypair(); $alicesk = sodiumcryptosignsecretkey($alice_kp); $alicepk = sodiumcryptosignpublickey($alice_kp);
$message = 'This is a test message.'; $signature = sodiumcryptosigndetached($message, $alicesk); if (sodiumcryptosignverifydetached($signature, $message, $alice_pk)) { echo 'OK', PHP_EOL; } else { throw new Exception('Invalid signature'); }
General-Use Polyfill
If your users are on PHP < 5.3, or you want to write code that will work whether or not the PECL extension is available, you'll want to use the ParagonIESodiumCompat class for most of your libsodium needs.
The above example, written for general use:
<?php
requireonce "/path/to/sodiumcompat/autoload.php";
$alicekp = ParagonIESodiumCompat::cryptosign_keypair(); $alicesk = ParagonIESodiumCompat::cryptosignsecretkey($alicekp); $alicepk = ParagonIESodiumCompat::cryptosignpublickey($alicekp);
$message = 'This is a test message.'; $signature = ParagonIESodiumCompat::cryptosigndetached($message, $alice_sk); if (ParagonIESodiumCompat::cryptosignverifydetached($signature, $message, $alicepk)) { echo 'OK', PHP_EOL; } else { throw new Exception('Invalid signature'); }
Generally: If you replace sodium with ParagonIESodium_Compat::, any code already written for the libsodium PHP extension should work with our polyfill without additional code changes.
Since this doesn't require a namespace, this API is exposed on PHP 5.2.
Since version 0.7.0, we have our own namespaced API (ParagonIE\Sodium\*) to allow brevity in software that uses PHP 5.3+. This is useful if you want to use our file cryptography features without writing ParagonIESodiumFile every time. This is not exposed on PHP < 5.3, so if your project supports PHP < 5.3, use the underscore method instead.
To learn how to use Libsodium, read Using Libsodium in PHP Projects.
Help, Sodium_Compat is Slow! How can I make it fast?
There are three ways to make it fast:
- Use a newer version of PHP (at least 7.2).
- Install the libsodium PHP extension from PECL.
- Only if the previous two options are not available for you:
ParagonIESodiumCompat::$fastMult = true;
without harming the security of your cryptography keys. If your processor isn't safe, then decide whether you
want speed or security because you can't have both.
How can I tell if sodium_compat will be slow, at runtime?
Since version 1.8, you can use the polyfillisfast() static method to determine if sodium_compat will be slow at runtime.
<?php
if (ParagonIESodiumCompat::polyfillisfast()) {
// Use libsodium now
$process->execute();
} else {
// Defer to a cron job or other sort of asynchronous process
$process->enqueue();
}
Documentation
First, you'll want to read the Libsodium Quick Reference. It aims to answer, "Which function should I use for [common problem]?".
If you don't find the answers in the Quick Reference page, check out Using Libsodium in PHP Projects.
Finally, the official libsodium documentation (which was written for the C library, not the PHP library) also contains a lot of insightful technical information you may find helpful.
API Coverage
Recommended reading: Libsodium Quick Reference
- Mainline NaCl Features
crypto_auth()
* cryptoauthverify()
* crypto_box()
* cryptoboxopen()
* crypto_scalarmult()
* crypto_secretbox()
* cryptosecretboxopen()
* crypto_sign()
* cryptosignopen()
- PECL Libsodium Features
cryptoaeadaegis128l_encrypt()
* cryptoaeadaegis128l_decrypt()
* cryptoaeadaegis256_encrypt()
* cryptoaeadaegis256_decrypt()
* cryptoaeadaes256gcm_encrypt()
* cryptoaeadaes256gcm_decrypt()
* cryptoaeadchacha20poly1305_encrypt()
* cryptoaeadchacha20poly1305_decrypt()
* cryptoaeadchacha20poly1305ietfencrypt()
* cryptoaeadchacha20poly1305ietfdecrypt()
* cryptoaeadxchacha20poly1305ietfencrypt()
* cryptoaeadxchacha20poly1305ietfdecrypt()
* cryptoboxxchacha20poly1305()
* cryptoboxxchacha20poly1305_open()
* cryptoboxseal()
* cryptoboxseal_open()
* crypto_generichash()
* cryptogenerichashinit()
* cryptogenerichashupdate()
* cryptogenerichashfinal()
* crypto_kx()
* cryptosecretboxxchacha20poly1305()
* cryptosecretboxxchacha20poly1305_open()
* crypto_shorthash()
* cryptosigndetached()
* cryptosigned25519pkto_curve25519()
* cryptosigned25519skto_curve25519()
* cryptosignverify_detached()
* For advanced users only:
* cryptocoreristretto255_add()
* cryptocoreristretto255fromhash()
* cryptocoreristretto255isvalid_point()
* cryptocoreristretto255_random()
* cryptocoreristretto255scalaradd()
* cryptocoreristretto255scalarcomplement()
* cryptocoreristretto255scalarinvert()
* cryptocoreristretto255scalarmul()
* cryptocoreristretto255scalarnegate()
* cryptocoreristretto255scalarrandom()
* cryptocoreristretto255scalarreduce()
* cryptocoreristretto255scalarsub()
* cryptocoreristretto255_sub()
* cryptoscalarmultristretto255_base()
* cryptoscalarmultristretto255()
* crypto_stream()
* cryptostreamkeygen()
* cryptostreamxor()
* cryptostreamxchacha20()
* cryptostreamxchacha20_keygen()
* cryptostreamxchacha20_xor()
* cryptostreamxchacha20xoric()
Other utilities (e.g. cryptokeypair())
* add()
* base642bin()
* bin2base64()
* bin2hex()
* hex2bin()
* cryptokdfderivefromkey()
* cryptokxclientsessionkeys()
* cryptokxserversessionkeys()
* cryptosecretstreamxchacha20poly1305initpush()
* cryptosecretstreamxchacha20poly1305_push()
* cryptosecretstreamxchacha20poly1305initpull()
* cryptosecretstreamxchacha20poly1305_pull()
* cryptosecretstreamxchacha20poly1305_rekey()
* pad()
* unpad()
Cryptography Primitives Provided
- X25519 - Elliptic Curve Diffie Hellman over Curve25519
- Ed25519 - Edwards curve Digital Signature Algorithm over Curve25519
- Xsalsa20 - Extended-nonce Salsa20 stream cipher
- ChaCha20 - Stream cipher
- Xchacha20 - Extended-nonce ChaCha20 stream cipher
- Poly1305 - Polynomial Evaluation Message Authentication Code modulo 2^130 - 5
- BLAKE2b - Cryptographic Hash Function
- SipHash-2-4 - Fast hash, but not collision-resistant; ideal for hash tables.
Features Excluded from this Polyfill
sodium_memzero()- Although we expose this API endpoint, we can't reliably
SodiumException.
sodiumcryptopwhash()- It's not feasible to polyfill scrypt or Argon2
SodiumException.
To detect support for Argon2i at runtime, use
ParagonIESodiumCompat::cryptopwhashis_available(), which returns a
boolean value (TRUE or FALSE).
Libsodium's HKDF API (cryptokdfhkdf_()) is not included because PHP has
its own HMAC features amd it was not deemed necessary.
PHPCompatibility Ruleset
For sodiumcompat users and that utilize PHPCompatibility in their CI process, there is now a custom ruleset available which can be used to prevent false positives being thrown by PHPCompatibility for the native PHP functionality being polyfilled by this repo.
You can find the repo for the PHPCompatibilityParagonieSodiumCompat ruleset here on Github and on Packagist.