#2 - Secure data with Authentication

Data: 2018-03-31 12:00 - PHP

Class to secure and authenticate small data packets in PHP.

<?php
class Secure {
    private static $method = 'AES-256-CBC';

    public static function encrypt($data, $key) {
        $key = hash('sha256', $key);
        $iv = random_bytes(16);

        $result = openssl_encrypt($data, self::$method, $key, OPENSSL_RAW_DATA, $iv);
        if ($result === false)
            return false;

        $hmac = hash_hmac('sha256', $iv . $result, hash('sha256', $key), true);
        return base64_encode($hmac . $iv . $result);
    }

    public static function decrypt($data, $key) {
        $bin_data = base64_decode($data);
        $hmac = substr($bin_data, 0, 32);
        $iv = substr($bin_data, 32, 16);
        $ciphered_data = substr($bin_data, 48);

        $key = hash('sha256', $key);

        $signature = hash_hmac('sha256', $iv . $ciphered_data, hash('sha256', $key), true);
        if (!hash_equals($hmac, $signature))
            return false;

        return openssl_decrypt($ciphered_data, self::$method, $key, OPENSSL_RAW_DATA, $iv);
    }
}

Previous snippet | Next snippet