DEV Community

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

Posted on

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. 🙂

Discussion (0)