Skip to content

Instantly share code, notes, and snippets.

@guillaumef
Last active June 4, 2021 12:38
Show Gist options
  • Save guillaumef/19f40a14e15c292daa5e74b40fdb5a85 to your computer and use it in GitHub Desktop.
Save guillaumef/19f40a14e15c292daa5e74b40fdb5a85 to your computer and use it in GitHub Desktop.
<?php
# PHP - low level AES 256 crypt/decrypt using openssl
# compatible with 'openssl enc' format
#
# Key: 32
# IV : 16
#
# Padding: PKCS7 (operated by openssl)
# EVP_BytesToKey: SHA256
#
# Magic: Salted__
#
# Author: Guillaume Fougnies
#
function EVP_BytesToKey($salt, $passphrase, $nkey, $niv)
{
$md_buf = "";
$key = "";
$iv = "";
$addmd = 0;
while (strlen($key) < $nkey || strlen($iv) < $niv) {
$md_sbuf = "";
if ($addmd) {
$md_sbuf .= $md_buf;
} else {
$addmd ++;
}
$md_sbuf .= $passphrase;
$md_sbuf .= $salt;
$md_buf = openssl_digest( $md_sbuf, 'SHA256', TRUE );
$md_buf2 = $md_buf;
if (strlen($key) < $nkey) {
$pos = $nkey - strlen($key);
$key .= substr($md_buf2, 0, $pos);
$md_buf2 = substr($md_buf2, $pos);
}
if (strlen($iv) < $niv) {
$iv .= substr($md_buf2, 0, $niv - strlen($iv));
}
}
return [$key, $iv];
}
function encrypt($string, $secret)
{
$crypttext = "Salted__";
$salt = random_bytes(8); /* php7 */
$crypttext .= $salt;
$keyiv = EVP_BytesToKey( $salt, $secret, 32, 16 );
$crypttext .= openssl_encrypt( $string, 'AES-256-CBC',
$keyiv[0], OPENSSL_RAW_DATA, $keyiv[1] );
return base64_encode( $crypttext );
}
function decrypt($string, $secret)
{
$data = base64_decode( $string );
$magic = substr($data, 0, 8);
$salt = substr($data, 8, 8);
$data = substr($data, 16);
if ($magic != "Salted__") {
return '';
}
$keyiv = EVP_BytesToKey( $salt, $secret, 32, 16 );
$string = openssl_decrypt( $data, 'AES-256-CBC',
$keyiv[0], OPENSSL_RAW_DATA, $keyiv[1] );
return $string;
}
### from console
if (count($argv)!=4) {
print "$argv[0] [e|d|ed] <password> <text>\n";
exit(1);
}
$mode = $argv[1];
$secret = $argv[2];
$text = $argv[3];
if ($mode == 'ed') {
$enc = encrypt( $text, $secret );
print "Encrypt >".$enc."<\n";
$dec = decrypt( $enc, $secret );
print "Decrypt >".$dec."<\n";
}
elseif ($mode == 'e') {
$enc = encrypt( $text, $secret );
print "Encrypt >".$enc."<\n";
}
elseif ($mode == 'd') {
$dec = decrypt( $text, $secret );
print "Decrypt >".$dec."<\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment