<?php
namespace App\Http\Controllers;

class EncController{
    private $public_key = "WrBEGoJnMnMhC/2hiaYypcmPwP9Z4p4/bNex0T/WUWA=";
    private $secret_key = "CEIBkv7QG1WoAoBO7Ny5cqzyJ5yCUwBMhnFYUBbCeTk=";

    public function encriptar($msg){
        $nonce = random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES);
        $nonceArr = array();
        for($i = 0; $i < strlen($nonce); $i++){
            $char = $nonce[$i];
            $ascii = ord($char);
            $nonceArr[] = $ascii;
        }
        $nonceJson = json_encode($nonceArr);
        $nonceStr = base64_encode($nonceJson);

        $encryption_key = sodium_crypto_box_keypair_from_secretkey_and_publickey(
            base64_decode($this->secret_key), 
            base64_decode($this->public_key));
        $encrypted = sodium_crypto_box($msg, $nonce, $encryption_key);
        $encryptedArr = array();
        for($i = 0; $i < strlen($encrypted); $i++){
            $char = $encrypted[$i];
            $ascii = ord($char);
            $encryptedArr[] = $ascii;
        }
        $encryptedJson = json_encode($encryptedArr);
        $encryptedStr = base64_encode($encryptedJson);

        return base64_encode($encryptedStr . "|" . $nonceStr);
    }

    public function desencriptar($enc){
        $dec = base64_decode($enc);
        $decArr = explode("|", $dec);
        $nonceDec = base64_decode($decArr[1]);
        $caddec = base64_decode($decArr[0]);
        $nonceArr = json_decode($nonceDec);
        $cadArr = json_decode($caddec);

        $nonceF = "";
        foreach($nonceArr as $asciiF){
            $nonceF .= chr($asciiF);
        }

        $cadF = "";
        foreach($cadArr as $asciiF){
            $cadF .= chr($asciiF);
        }

        $encryption_key_dec = sodium_crypto_box_keypair_from_secretkey_and_publickey(
            base64_decode($this->secret_key), 
            base64_decode($this->public_key)
        );
        $decrypted = sodium_crypto_box_open($cadF, $nonceF, $encryption_key_dec);

        return $decrypted;
    }
}