AKZN Notes

Archives for My Lazy and Forgetful Mind

The Most Secure Way to Encrypt and Decrypt Your Data on PHP

The Most Secure Way to Encrypt and Decrypt Your Data

Data security is a critical aspect of modern applications, and choosing a robust encryption method is paramount to protect sensitive information. In this guide, we'll explore a secure approach to encrypt and decrypt data using PHP and OpenSSL.

Generate Two Random Keys

Before we delve into the encryption and decryption process, let's create two random keys. These keys will be used to strengthen the encryption.

// Create The First Key
echo base64_encode(openssl_random_pseudo_bytes(32));

// Create The Second Key
echo base64_encode(openssl_random_pseudo_bytes(64));

Save these keys securely, preferably in your application's configuration file.

// Save The Keys In Your Configuration File
define('FIRSTKEY', 'Lk5Uz3slx3BrAghS1aaW5AYgWZRV0tIX5eI0yPchFz4=');
define('SECONDKEY', 'EZ44mFi3TlAey1b2w4Y7lVDuqO+SRxGXsa7nctnr/JmMrA2vN6EJhrvdVZbxaQs5jpSe34X3ejFK/o9+Y5c83w==');

Now, let's proceed with the encryption and decryption functions.

Encryption Function

<?php
function secured_encrypt($data)
{
    $first_key = base64_decode(FIRSTKEY);
    $second_key = base64_decode(SECONDKEY);    

    $method = "aes-256-cbc";    
    $iv_length = openssl_cipher_iv_length($method);
    $iv = openssl_random_pseudo_bytes($iv_length);

    $first_encrypted = openssl_encrypt($data, $method, $first_key, OPENSSL_RAW_DATA, $iv);    
    $second_encrypted = hash_hmac('sha3-512', $first_encrypted, $second_key, TRUE);

    $output = base64_encode($iv . $second_encrypted . $first_encrypted);    
    return $output;        
}
?>

Decryption Function

<?php
function secured_decrypt($input)
{
    $first_key = base64_decode(FIRSTKEY);
    $second_key = base64_decode(SECONDKEY);            
    $mix = base64_decode($input);

    $method = "aes-256-cbc";    
    $iv_length = openssl_cipher_iv_length($method);

    $iv = substr($mix, 0, $iv_length);
    $second_encrypted = substr($mix, $iv_length, 64);
    $first_encrypted = substr($mix, $iv_length + 64);

    $data = openssl_decrypt($first_encrypted, $method, $first_key, OPENSSL_RAW_DATA, $iv);
    $second_encrypted_new = hash_hmac('sha3-512', $first_encrypted, $second_key, TRUE);

    if (hash_equals($second_encrypted, $second_encrypted_new))
        return $data;

    return false;
}
?>

These functions (secured_encrypt and secured_decrypt) utilize two keys and a combination of AES-256-CBC encryption and SHA3-512 HMAC for added security. The IV is randomly generated for each encryption operation.

Feel free to integrate these functions into your PHP application to ensure a robust and secure way to encrypt and decrypt your sensitive data.

Leave a Reply

Your email address will not be published.