Skip to content

Instantly share code, notes, and snippets.

@shreshthmohan
Last active August 8, 2022 10:44
Show Gist options
  • Save shreshthmohan/d9b89cd9cb7405942290883eff891611 to your computer and use it in GitHub Desktop.
Save shreshthmohan/d9b89cd9cb7405942290883eff891611 to your computer and use it in GitHub Desktop.
Understanding some php code
<?php
function encrypt($plainText,$key) {
// md5 hash of $key, then output is a hex number
// convert hex output of md5() to binary, but I think it should be "hex2bin"
$key = hextobin(md5($key));
// initialisation vector needed for decryption later too
// packs data into binary string, treat data to be in unsigned char format. https://www.php.net/manual/en/function.pack.php
$initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
// generate encypted data
// https://stackoverflow.com/questions/34871579/how-to-encrypt-plaintext-with-aes-256-cbc-in-php-using-openssl/34871988#34871988
$openMode = openssl_encrypt($plainText, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $initVector);
// convert output of openssl to hexadecimal
$encryptedText = bin2hex($openMode);
// return encrypted text
return $encryptedText;
}
// exactly the reverse of encrypt function above
function decrypt($encryptedText,$key) {
$key = hextobin(md5($key));
$initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
$encryptedText = hextobin($encryptedText);
$decryptedText = openssl_decrypt($encryptedText, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $initVector);
return $decryptedText;
}
function pkcs5_pad ($plainText, $blockSize) {
// find how many characters the text is short for a multiple of block size
$pad = $blockSize - (strlen($plainText) % $blockSize);
// repeat the character as many times as needed to have the length be equal to a a block size multiple
return $plainText . str_repeat(chr($pad), $pad);
}
// byte by byte conversion to binary
// not completely sure about why they aren't using hex2bin
// probably they want the bytewise conversion not number conversion
function hextobin($hexString) {
$length = strlen($hexString); $binString="";
$count=0;
while($count<$length)
{
$subString =substr($hexString,$count,2);
$packedString = pack("H*",$subString);
if ($count==0)
{
$binString=$packedString;
}
else
{
$binString.=$packedString;
}
$count+=2;
}
return $binString;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment