Skip to content

Instantly share code, notes, and snippets.

@evansims
Last active March 18, 2024 08:39
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save evansims/b14f8af6055fee34edbe68ad5af9e597 to your computer and use it in GitHub Desktop.
Save evansims/b14f8af6055fee34edbe68ad5af9e597 to your computer and use it in GitHub Desktop.
AES-256-GCM w/ PHP 7.1+ OpenSSL
<?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;
}
}
<?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);
}
@pietrocaporale
Copy link

Thanks a lot Evan, now I'will look for long file encryption.

@SwanYooshy
Copy link

Nice work, thank you!

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