Secured.php

<?php

namespace ROF\Resource;

class Secured {

    private $hashTable = [];

    public function __construct($valuesList, $lookupKey){
        $this->loadHashTable();
        if (!$this->isSecured($lookupKey)){
            $this->secureValue($valuesList,$lookupKey);
        }
    }

 
    private function pkcs7_pad($data, $size)
    {
        $length = $size - strlen($data) % $size;
        return $data . str_repeat(chr($length), $length);
    }
    private function pkcs7_unpad($data)
    {
        return substr($data, 0, -ord($data[strlen($data) - 1]));
    }

    private function getEncryptedValue($rawValue){
        $encryption_key = 'am_dumb_key';
        $iv_size = 16; // 128 bits
        //$iv = openssl_random_pseudo_bytes($iv_size, $strong);
        $iv = 'weak nothing1234';
        $enc_value = openssl_encrypt(
            $this->pkcs7_pad($rawValue, 16), // padded data
            'AES-256-CBC',        // cipher and mode
            $encryption_key,      // secret key
            0,                    // options (not used)
            $iv                   // initialisation vector
        );
        return $enc_value;
    }

    private function getDecryptedValue($encryptedValue){
        $encryption_key = 'am_dumb_key';
        $iv = 'weak nothing1234';
        $decryptedValue = $this->pkcs7_unpad(openssl_decrypt(
            $encryptedValue,
            'AES-256-CBC',
            $encryption_key,
            0,
            $iv
        ));
        return $decryptedValue;
    }

    private function secureValue($valuesList,$lookupKey){
        $parts = explode('.',$lookupKey);
        $soughtValue = array_pop($parts);
        if (!isset($valuesList[$soughtValue])){
            throw new \Exception("Cannot find a value for lookup key '{$lookupKey}'");
        }
        $rawValue = $valuesList[$soughtValue];
        $encryptedValue = $this->getEncryptedValue($rawValue);
        // var_dump($encryptedValue);
        // var_dump($this->getDecryptedValue($encryptedValue));
        // var_dump($rawValue);
        $hashedKey = password_hash($lookupKey, PASSWORD_BCRYPT);
        $this->hashTable[$hashedKey] = $encryptedValue;
    }
    private function isSecured($lookupKey){
        foreach ($this->hashTable as $hashedLookupKey=>$encryptedValue){
            if (password_verify($lookupKey,$hashedLookupKey)){
                return TRUE;
            }
        }
        return FALSE;
    }
    private function loadHashTable(){
        $hashTableFile = __DIR__.'/hash_table_file.json';
        if (!file_exists($hashTableFile)){
            $this->hashTable = [];
        } else {
            $this->hashTable = json_decode(file_get_contents($hashTableFile),TRUE);
        }
    }
}

?>