Last active
October 3, 2024 11:19
-
-
Save evansims/b14f8af6055fee34edbe68ad5af9e597 to your computer and use it in GitHub Desktop.
AES-256-GCM w/ PHP 7.1+ OpenSSL
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 | |
public function decrypt($secret, $data) | |
{ | |
$secret = hex2bin($secret); | |
$iv = base64_decode(substr($data, 0, 16), true); | |
$data = base64_decode(substr($data, 16), true); | |
$tag = substr($data, strlen($data) - 16); | |
$data = substr($data, 0, strlen($data) - 16); | |
try { | |
return openssl_decrypt( | |
$data, | |
'aes-256-gcm', | |
$secret, | |
OPENSSL_RAW_DATA, | |
$iv, | |
$tag | |
); | |
} catch (\Exception $e) { | |
return false; | |
} | |
} |
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 | |
public function encrypt($secret, $data) | |
{ | |
$secret = hex2bin($secret); | |
$iv = random_bytes(12); | |
$tag = ''; | |
$encrypted = openssl_encrypt( | |
$data, | |
'aes-256-gcm', | |
$secret, | |
OPENSSL_RAW_DATA, | |
$iv, | |
$tag, | |
'', | |
16 | |
); | |
return base64_encode($iv) . base64_encode($encrypted . $tag); | |
} |
Nice work, thank you!
Sorry about this dumb question but what is the purpose of using a hex string, please? Surely a hacker would know about hex2bin(), no?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot Evan, now I'will look for long file encryption.