PHP7 Sodium Encryption Decryption
PHP7.2 introduces modern cryptography extensions to make encryption, decryption techniques more protected. That provides high security and protect our system from the advanced hackers. The cryptography is hard to design and implement. The Sodium Crypto Library is one of them. It is a fork of NaCL (Network and Cryptography Library).
Sodium Crypto Library is modern, installable, easy to use, cross compatible library that is generally used for network and data communication, high speed encryption decryption and digital signatures.
These are the following features of the Sodium Crypto Library-
- Public and shared key signatures
- Keyed hashing
- Authenticated public key encryption
- Authenticated shared key encryption
- Secured pseudo random number generation
Install PHP Libsodium in Wampserver
To use Sodium crypto, first we have to install the Libsodium using PECL. These are the steps -
- Download the libsodium from here -
windows.php.net/downloads/pecl/releases/libsodium/1.0.2/php_libsodium-1.0.2-7.0-ts-vc14-x64.zip and extract the folder.
- Copy php_libsodium.dll file and paste to php folder(wamp\bin\php\php7.2.18). Make sure to paste in the right PHP version folder that you are using.
- Click on the Wamp system tray icon, go to PHP -> PHP Extensions -> Sodium and enable Sodium.
- Now Sodium extension is ready to use.
To make sure that libsodium is enabled in the server or not, let's check its version using the following code -
<?php var_dump([ SODIUM_LIBRARY_MAJOR_VERSION, SODIUM_LIBRARY_MINOR_VERSION, SODIUM_LIBRARY_VERSION ]); ?>
It returns this output -
array (size=3) 0 => int 10 1 => int 2 2 => string '1.0.17' (length=6)
Algorithms in Sodium
These are some algorithms that we can use with Sodium -
- Salsa20, ChaCha20
- Argon2, Scrypt
Sodium Encryption Decryption Example
In this example, we have used random_bytes() to generates cryptographically secure pseudo-random bytes and generated both secure key using sodium SODIUM_CRYPTO_SECRETBOX_KEYBYTES and nonce using Sodium SODIUM_CRYPTO_SECRETBOX_NONCEBYTES. After that, we have encrypted the text message using sodium_crypto_secretbox() method and decrypted the text using sodium_crypto_secretbox_open() method.
<?php $text = 'Encrypt Decrypt this text using Sodium'; // Create an encryption key and a nonce $secret_key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES); $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); // Encrypting Text $encryptedtext = sodium_crypto_secretbox($text, $nonce, $secret_key); // Decrypting Text $plaintext = sodium_crypto_secretbox_open($encryptedtext , $nonce, $secret_key); echo $plaintext === $text ? 'Encryption Success' : 'Error'; ?>