Skip to content

Instantly share code, notes, and snippets.

@RiANOl
Forked from anonymous/gist:957281
Last active April 4, 2024 08:34
Show Gist options
  • Star 53 You must be signed in to star a gist
  • Fork 21 You must be signed in to fork a gist
  • Save RiANOl/1077723 to your computer and use it in GitHub Desktop.
Save RiANOl/1077723 to your computer and use it in GitHub Desktop.
AES128 / AES256 CBC with PKCS7Padding in PHP
function aes256EcbPkcs7PaddingEncrypt($key, $data) {
$padding = 16 - (strlen($data) % 16);
$data .= str_repeat(chr($padding), $padding);
return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, hash('SHA256', $key, true), $data, MCRYPT_MODE_ECB);
}
function aes256EcbPkcs7PaddingDecrypt($key, $data) {
$data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, hash('SHA256', $key, true), $data, MCRYPT_MODE_ECB);
$padding = ord($data[strlen($data) - 1]);
return substr($data, 0, -$padding);
}
@somnathbaksi
Copy link

Nice ,,, keep it up

@bojanmartin
Copy link

I'm not sure if there's another page explaining the context of this gist. For anyone who got here without context (e.g. from Google) - like I did - please note that creating an IV using str_repeat("\0", 16) makes this code absolutely not production-ready! See Block cipher mode of operation at Wikipedia for more details. In short, "In CBC mode, the IV must... be unpredictable at encryption time."

@texelate
Copy link

@jruizinmind
Copy link

Superb!

@demenvil
Copy link

Nice ty !

@dafahan
Copy link

dafahan commented Mar 29, 2024

it's deprecated on php 7+

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