Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encrypt / decrypt AES with Libsodium-PHP


I need to encrypt/decrypt data with PHP. I am completely new to this, however I have read that Libsodium-PHP is the best tool for AES encryption. Much like the other PHP encryption libraries I have researched Libsoduim-PHP seemed to offer almost no documentation of how to use the library (that I was able to find). Can anyone that has experience with PHP encryption either point me in the direction of a good learning resource or write a few lines of sample code using Libsoduim-PHP?
Thank you very much for the help,
Atlas

like image 200
atlas81887 Avatar asked Dec 27 '15 04:12

atlas81887


People also ask

How do you AES encrypt and decrypt?

The AES algorithm is a symmetrical block cipher that encrypts and decrypts data in blocks of 256 bits. The decryption block uses the AES algorithm to decrypt the boot loader image and configuration data before configuring the FPGA portion of the device. If encryption is not used, the AES decryptor is bypassed.

How do you use encrypt and decrypt in PHP?

In PHP, Encryption and Decryption of a string is possible using one of the Cryptography Extensions called OpenSSL function for encrypt and decrypt. openssl_encrypt() Function: The openssl_encrypt() function is used to encrypt the data. Parameters: $data: It holds the string or data which need to be encrypted.

What is sodium PHP?

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.

What is encryption in PHP?

PHP encryption is important to the privacy and safety of your data. In practical terms, PHP encryption uses algorithms (sometimes called hashing algorithms) to translate the “clear” data into encrypted text that requires very specific decryption processes to “decode” the data back to the clean version.


2 Answers

PHP Version >= 7.2

If you are using PHP >= 7.2 use inbuilt sodium core extension instead.

Sample implementation

<?php 
//Simple Usage

/**
* Encrypt a message
* 
* @param string $message - message to encrypt
* @param string $key - encryption key
* @return string
*/
function safeEncrypt($message, $key)
{
    $nonce = random_bytes(
        SODIUM_CRYPTO_SECRETBOX_NONCEBYTES
    );

    $cipher = base64_encode(
        $nonce.
        sodium_crypto_secretbox(
            $message,
            $nonce,
            $key
        )
    );
    sodium_memzero($message);
    sodium_memzero($key);
    return $cipher;
}

/**
* Decrypt a message
* 
* @param string $encrypted - message encrypted with safeEncrypt()
* @param string $key - encryption key
* @return string
*/
function safeDecrypt($encrypted, $key)
{   
    $decoded = base64_decode($encrypted);
    if ($decoded === false) {
        throw new Exception('Scream bloody murder, the encoding failed');
    }
    if (mb_strlen($decoded, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
        throw new Exception('Scream bloody murder, the message was truncated');
    }
    $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
    $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

    $plain = sodium_crypto_secretbox_open(
        $ciphertext,
        $nonce,
        $key
    );
    if ($plain === false) {
         throw new Exception('the message was tampered with in transit');
    }
    sodium_memzero($ciphertext);
    sodium_memzero($key);
    return $plain;
}
//Encrypt & Decrypt your message
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);

$enc = safeEncrypt('Encrypt This String...', $key); //generates random  encrypted string (Base64 related)
echo $enc;
echo '<br>';
$dec = safeDecrypt($enc, $key); //decrypts encoded string generated via safeEncrypt function 
echo $dec;
like image 77
M_R_K Avatar answered Nov 01 '22 20:11

M_R_K


Much like the other PHP encryption libraries I have researched Libsoduim-PHP seemed to offer almost no documentation of how to use the library (that I was able to find).

From the libsodium-php Github page you will find a direct link to a free online book that covers everything you need to know to get started with libsodium.

The final chapter contains libsodium recipes, but each chapter contains detailed usage information.

If you specifically need AES, read this.

If you don't have an "AES-or-bust" requirement hanging over your head, where failure to specifically use AES means your department gets axed and your developers face a firing squad, you should consider just using crypto_secretbox which uses Xsalsa20 for encryption and attaches a Poly1305 authentication tag. (This is authenticated encryption, which you want to use almost always.)

Also look into Halite if you want easy-mode.

like image 16
Scott Arciszewski Avatar answered Nov 01 '22 21:11

Scott Arciszewski