Created
January 26, 2018 11:08
-
-
Save FelipeGangrel/61817ecaf9bbf5e78066473a19b848cf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Cripto | |
{ | |
/** | |
* O salt será usado para negar ou aceitar a request e também para gerar uma chave criptografica | |
* @var string | |
*/ | |
protected $salt; | |
/** | |
* O array to post | |
* @var array | |
*/ | |
protected static $dados; | |
/** | |
* @param string $salt | |
*/ | |
public function setSalt($salt) | |
{ | |
$this->salt = $salt; | |
return $this; | |
} | |
/** | |
* Encriptando dados | |
* @param string $string | |
* @return string | |
*/ | |
private function encriptar($string) | |
{ | |
$key = $this->salt; | |
// Gerando um vetor de inicialização | |
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); | |
// Encriptando os dados usando AES 256 em modo DBC | |
$encriptado = openssl_encrypt($string, 'aes-256-cbc', $key, 0, $iv); | |
// O $iv é tão importante quanto a chave para a decriptação, então concatenaremos os dados usando um separador único (::) | |
return base64_encode($encriptado . '::' . $iv); | |
} | |
/** | |
* Decriptando dados | |
* @param string $string | |
* @return void | |
*/ | |
private function decriptar($string) | |
{ | |
$key = $this->salt; | |
// Recuperando a chave e o $iv | |
list($encriptado, $iv) = explode('::', base64_decode($string), 2); | |
return openssl_decrypt($encriptado, 'aes-256-cbc', $key, 0, $iv); | |
} | |
/** | |
* Enviar requisição | |
* @param string $url | |
* @param array $dados | |
* @return void | |
*/ | |
public function enviar($url, $dados) | |
{ | |
$array = []; | |
$array['salt'] = hash('sha256',$this->salt); | |
$array['conteudo'] = $this->encriptar(json_encode($dados)); | |
$query = http_build_query($array); | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $url); | |
curl_setopt($ch, CURLOPT_POST, 1); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $query); | |
curl_exec($ch); | |
curl_close($ch); | |
} | |
/** | |
* Tratar requisição recebida | |
* @param array $post | |
* @return boolean | |
*/ | |
public function receber($post) | |
{ | |
if( hash('sha256',$this->salt) != $post['salt'] ) return false; | |
self::$dados = json_decode($this->decriptar($post['conteudo']), true); | |
return true; | |
} | |
/** | |
* Retorna o conteúdo do POST sem o cripto | |
* @return array | |
*/ | |
public function getDados() | |
{ | |
return self::$dados; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment