<?php

class Securite
{
    public static function getKey()
    {
        return '132456512151efzsef4s5f1sdf545fs5dsf5ds4fghtdxlgjkezrl23!!;::,;:ezsfzesr44erz';
    }

    public static function getCipher()
    {
        return 'AES-256-CBC';
    }

    /**
     * getIv
     *
     * @return string
     */
    public static function getIv() : string
    {
        return 'InitVecteur98737';
    }

    public static function creationTokenCSRF()
    {
        $key = Securite::getKey();
        $key = openssl_digest($key, 'SHA256', true);
        $plaintext = time()+(60*60*5);

        $ivlen = openssl_cipher_iv_length(Securite::getCipher());
        $iv = openssl_random_pseudo_bytes($ivlen);
        // binary cipher
        $ciphertextRaw = openssl_encrypt($plaintext, Securite::getCipher(), $key, OPENSSL_RAW_DATA, $iv);
        // or replace OPENSSL_RAW_DATA & $iv with 0 & bin2hex($iv) for hex cipher (eg. for transmission over internet)

        // or increase security with hashed cipher; (hex or base64 printable eg. for transmission over internet)
        $hmac = hash_hmac('sha256', $ciphertextRaw, $key, true);
        $token = base64_encode($iv . $hmac . $ciphertextRaw);
        $_SESSION['CSRF'][$token] = $plaintext;
        return $token;

    }

    public static function decryptTokenCSRF($ciphertext)
    {
        if(!count(getValueAll()))
        {
            return  true;
        }

        foreach($_SESSION['CSRF'] as $key => $value)
        {
            if($value < time())
            {
                unset($_SESSION['CSRF'][$key]);
            }
        }

        $c = base64_decode($ciphertext);

        $key = openssl_digest(Securite::getKey(), 'SHA256', true);
    
        $ivlen = openssl_cipher_iv_length(Securite::getCipher());
    
        $iv = substr($c, 0, $ivlen);
        $hmac = substr($c, $ivlen, $sha2len = 32);
        $ciphertextRaw = substr($c, $ivlen + $sha2len);
        $originalPlaintext = openssl_decrypt($ciphertextRaw, Securite::getCipher(), $key, OPENSSL_RAW_DATA, $iv);

        
        // $calcmac = hash_hmac('sha256', $ciphertextRaw, $key, true);
        // if (hash_equals($hmac, $calcmac))
        //     return $originalPlaintext ;
        // return false;

        if($originalPlaintext === false)
        {
            return false;
        }

        if(isset($_SESSION['CSRF'][$ciphertext]))
        {
            return true;
        } else {
            return false;
        }
    }

    public static function controleCSRF()
    {
        return true;

        // if(isset($_SESSION['token']) && isset($_SESSION['token_time']) && getValue('token'))
        // {
            
        //     //Si le jeton de la session correspond à celui du formulaire
        //     if($_SESSION['token'] == getValue('token'))
        //     {
        //         //On stocke le timestamp qu'il était il y a 15 minutes
        //         $timestamp_ancien = time() - (5*60);
        //         //Si le jeton n'est pas expiré
        //         if($_SESSION['token_time'] < $timestamp_ancien)
        //         {
        //             $msg = trad('Le formulaire a expiré. Veuillez recharger la page, s\'il vous plait.');
        //             Affichage::messageJS($msg);
        //             exit;
        //         }
        //     }else
        //     {
        //         $msg = trad('Un problème est survenu sur le formulaire');
        //         Affichage::messageJS($msg);
        //         exit;
        //     }
        // }else{
            
        //     $msg = trad('Un problème est survenu sur le formulaire');
        //     Affichage::messageJS($msg);
        //     exit;
        // }
    }

    public static function setToken(&$data)
    {
        $token = uniqid(rand(), true);
        $data['token'] = $_SESSION['token'] = $token;
        $data['token_time'] = $_SESSION['token_time'] = time();
    }

    public static function tokenIDOR($no_doc, $action)
    {
        return hash('sha256',$_SESSION['Session_Login'].$no_doc.$action.'kjsdf$&&g5458584$$$ù$ùsdfsdfbbg98752!!!');
    }

    public static function testTokenIDOR($no_doc, $action, $token)
    {
        if(hash('sha256',$_SESSION['Session_Login'].$no_doc.$action.'kjsdf$&&g5458584$$$ù$ùsdfsdfbbg98752!!!') != $token)
            exit;
    }

    /**
     * decodeChiffrageFromMagic
     *
     * @param  string $content
     * @return string|false
     */
    public static function decodeChiffrageFromGetContent($content)
    {
        if($content == '')
            return '';
        $c = base64_decode($content);
        $cipher = Securite::getCipher();
        $key = Securite::getkey();
        $iv = Securite::getIv();
        return openssl_decrypt($c, $cipher, $key, OPENSSL_RAW_DATA, $iv);
    }
        
    /**
     * encodeChiffrageFormMagic
     *
     * @param  string $content
     * @return string
     */
    public static function encodeChiffrageFormGetContent($content)
    {
        if($content == '')
            return '';
        $cipher = Securite::getCipher();
        $key = Securite::getkey();
        $iv = Securite::getIv();
        $c = openssl_encrypt($content, $cipher, $key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($c);
    }
}