Skip to content

Instantly share code, notes, and snippets.

@imacruz
Created May 25, 2023 20:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imacruz/af29a1ce5599f02126fc41d84855dbc0 to your computer and use it in GitHub Desktop.
Save imacruz/af29a1ce5599f02126fc41d84855dbc0 to your computer and use it in GitHub Desktop.
Criptograr e descriptografar usando aes_encript
<?php
private function getAppKey(): string
{
return config("app.aes_key");
}
function encrypt(string $data): string
{
$key = $this->getAppKey();
$method = 'aes-128-ecb';
$ivSize = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($ivSize);
$encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
$encrypted = strtoupper(implode(null, unpack('H*', $encrypted)));
return $encrypted;
}
function decrypt(string $data): string
{
$key = $this->getAppKey();
$method = 'aes-128-ecb';
$data = pack('H*', $data);
$ivSize = openssl_cipher_iv_length($method);
$iv = $iv = openssl_random_pseudo_bytes($ivSize);
$decrypted = openssl_decrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
return trim($decrypted);
}
public function scopeNome($query, $value)
{
return $query->whereRaw("LOWER(CONVERT(CAST(CONVERT(AES_DECRYPT(UNHEX(nome), ?) USING UTF8) AS BINARY) USING UTF8)) LIKE ?", [$this->getAppKey(),'%'.strtolower($value).'%']);
}
@imacruz
Copy link
Author

imacruz commented May 25, 2023

Exemplos de SQL utilizando a conversão:

select
	count(*) as aggregate
from
	clientes
where
	(`cliente_id` = 43)
	and LOWER(CONVERT(CAST(CONVERT(AES_DECRYPT(UNHEX(nome), 'Z[%<cs18iF#*g6!') USING UTF8) AS BINARY) USING UTF8)) LIKE '%allison%'`

@imacruz
Copy link
Author

imacruz commented May 25, 2023

Usando mysql e maria DB até o momento presente tudo ok
Atributo no banco devera ser varbinary(255) ou blob

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment