DEV Community

Cover image for Secure Your Data with AES 256 bit Encryption and Decryption method using PHP
Deepak Singh
Deepak Singh

Posted on

6 1

Secure Your Data with AES 256 bit Encryption and Decryption method using PHP

So today let’s discuss another method of data encryption and decryption using PHP AES-256-CBC and OpenSSL to cipher[encryption] and decipher[decryption] any string in the PHP.

Encryption is a common method to protect data in the cyber world, which converts plain text into a long ciphertext constructed with random alphanumeric characters.

We are using AES Advanced Encryption Standard with 256 bits key length. The following image shows how symmetric key encryption works:

Image description
Let’s see the main recipe of the topic:

class secureToke
{
    private static $secretKey = 'Your Desired key(Alphanumeric)';
    private static $secretIv = 'www.domain.com';
    private static $encryptMethod = "AES-256-CBC";
    public static function tokenencrypt($data)
    {
        $key = hash('sha256', self::$secretKey);
        $iv = substr(hash('sha256', self::$secretIv), 0, 16);
        $result = openssl_encrypt($data, self::$encryptMethod, $key, 0, $iv);
        return $result = base64_encode($result);
    }
    public static function tokendecrypt($data)
    {
        $key = hash('sha256', self::$secretKey);
        $iv = substr(hash('sha256', self::$secretIv), 0, 16);
        $result = openssl_decrypt(base64_decode($data), self::$encryptMethod, $key, 0, $iv);
        return $result;
    }
}
Enter fullscreen mode Exit fullscreen mode

Encryption method:

$tokenencrypt = secureToken::tokenencrypt($token);
Enter fullscreen mode Exit fullscreen mode

Decryption method:

$tokendecrypt = secureToken::tokendecrypt($encryptedtoken);
Enter fullscreen mode Exit fullscreen mode

Voila! it’s done… Now you can encrypt your entire data on the webspace and make them secure. 🙂

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay