<?php
namespace common\components;
use yii;

Class Encryption {
    // DECLARE THE REQUIRED VARIABLES
    const ENC_METHOD = "AES-256-CBC"; // THE ENCRYPTION METHOD.
    const ENC_KEY = "HHDJYRIBXM_S+J28"; // ENCRYPTION KEY
    const ENC_IV = "VSDJSLWI_+XXXTSYSKS"; // ENCRYPTION IV.
    const ENC_SALT = "xS$"; // THE SALT FOR PASSWORD ENCRYPTION ONLY.

    // THIS FUNCTION WILL ENCRYPT THE PASSED STRING
    public static function Encrypt($string) {
        try {
            $output = false;
            $key = hash('sha256', self::ENC_KEY);
            // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
            $iv = substr(hash('sha256', self::ENC_IV), 0, 16);
            $output = openssl_encrypt($string, self::ENC_METHOD, $key, 0, $iv);
            $output = base64_encode($output);
            return $output;
        } catch (Exception $e) {
            return "Caught exception: " . $e->getMessage();
        }
    }

    // THIS FUNCTION WILL DECRYPT THE ENCRYPTED STRING.
    public static function Decrypt($string) {
        try {
            $output = false;
            // hash
            $key = hash('sha256', self::ENC_KEY);
            // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
            $iv = substr(hash('sha256', self::ENC_IV), 0, 16);

            $output = openssl_decrypt(base64_decode($string), self::ENC_METHOD, $key, 0, $iv);
            return $output;
        } catch (Exception $e) {
            return "Caught exception: " . $e->getMessage();
        }
    }

    // THIS FUNCTION FOR PASSWORDS ONLY, BECAUSE IT CANNOT BE DECRYPTED IN FUTURE.
    public function EncryptPassword($Input) {
        try {
            if (!isset($Input) || $Input == null || empty($Input)) {
                return false;
            }

            // GENERATE AN ENCRYPTED PASSWORD SALT
            $SALT = $this->Encrypt($this->ENC_SALT);
            $SALT = md5($SALT);
            // PERFORM MD5 ENCRYPTION ON PASSWORD SALT.
            // ENCRYPT PASSWORD
            $Input = md5($this->Encrypt(md5($Input)));
            $Input = $this->Encrypt($Input);
            $Input = md5($Input);

            // PERFORM ANOTHER ENCRYPTION FOR THE ENCRYPTED PASSWORD + SALT.
            $Encrypted = $this->Encrypt($SALT) . $this->Encrypt($Input);
            $Encrypted = sha1($Encrypted . $SALT);

            // RETURN THE ENCRYPTED PASSWORD AS MD5
            return md5($Encrypted);
        } catch (Exception $e) {
            return "Caught exception: " . $e->getMessage();
        }
    }

}
?>