How to Encrypt And Decrypt String in PHP7

This tutorial help to understand encrypt and decrypt a string in php7.3. I have also shared How To Encrypt and Decrypt strings in PHP 5. As you aware sodium is replaced mcrypt method (which is officially being deprecated) in PHP7.3.

The mycrpt() function is used to encrypt and dycrypt() string in PHP 5, but this function is deprecated in PHP 7.3.

We will use Sodium PHP encryption library. This is an open-source library and converts string data into encrypted text and vise versa.The Sodium PHP encryption library help to protect your data and secure every field in your entities with this tiny encryption library.

Two-Way Encryption In PHP7

Let’s Integrate Sodium PHP encryption library with php 7 application, We will encrypt a string using salt/key and decrypt the string with the same salt/key.

How To Install Sodium PHP encryption library

You can install the encryption/decryption library by using composer. Please use the following command to install into the application:

composer require internetpixels/sodium-encryption

How To Configure Sodium Encryption

We need to pass the secret key and public key into Sodium libs. This is one-time setup keys and is not allowed to change over time.

<?php
// Update the keys (create a new unique keypair)!
\InternetPixels\SodiumEncryption\EncryptionManager::setKeys(
    'secret key..',
    'public key..'
);
?>

How To Create nonce in Sodium Encryption

The nounce is help to encrypt and decrypt data, You can create unique nonce per entity wise. The EncryptionManager::generateNonce() method helps to create nonce.

How To Encrypt String in PHP

The PHP Sodium Encryption library provides encrypt($param1, param2) method to encrypt data. This method takes the first params as a source string and the second is nounce.

<?php
$string = 'Hi, This is PHPFlow.';
$nonce = EncryptionManager::generateNonce();

$encrypted = EncryptionManager::encrypt($string, $nonce);
?>

How To Decrypt String in PHP

The PHP Sodium Encryption library provides decrypt($param1, param2) method to decrypt data. The first parameter is an encrypted string and the second one is nonce.

<?php
$string = EncryptionManager::decrypt($encrypted, $nonce);
?>

4 thoughts on “How to Encrypt And Decrypt String in PHP7

Leave a Reply

Your email address will not be published. Required fields are marked *