I am trying to create the encrypt PHP algorithm from this thread:
how to sync encryption between delphi and php using dcpcrypt (see shunty's reply)
Here is what I have so far:
function encrypt($str, $key)
{
$keysize = mcrypt_get_key_size(MCRYPT_DES, MCRYPT_MODE_CBC);
$ivbytes = array(72, 163, 99, 62, 219, 111, 163, 114);
$iv = implode(array_map("chr", $ivbytes));
$pad = ord($str[strlen($str) - 1]);
$enc = substr($str, 0, strlen($str) - $pad);
$enc = base64_encode($str);
$k = mhash(MHASH_SHA1, $key);
//return substr($dec, 0, strlen($dec) - $pad);
$dec = mcrypt_encrypt(MCRYPT_DES, substr($k, 0, $keysize), $enc, MCRYPT_MODE_CBC, $iv);
return $dec;
}
I'm not sure what I'm doing wrong but testing it with this:
echo encrypt("this is a test", "test");
Gives the output: =ž«RCdrçb˜hý’¯á·OÊ when it should give: WRaG/8xlxqqcTAJ5UAk4DA==
Can anyone help me out in explaining where I am going wrong, would really appreciate the help I can get.
EDIT:
function encrypt_SO($str, $key)
{
$keysize = mcrypt_get_key_size(MCRYPT_DES, MCRYPT_MODE_CBC);
$ivbytes = array(72, 163, 99, 62, 219, 111, 163, 114);
$iv = implode(array_map("chr", $ivbytes));
$pad = ord($str[strlen($str) - 1]);
$enc = substr($str, 0, strlen($str) - $pad);
$k = mhash(MHASH_SHA1, $key);
//return substr($dec, 0, strlen($dec) - $pad);
$dec = mcrypt_encrypt(MCRYPT_DES, substr($k, 0, $keysize), $enc, MCRYPT_MODE_CBC, $iv);
return base64_encode($dec);
}
Moved the encoding to the end.
EDIT 2: Solution thanks to everyone's helpful posts:
function encrypt_SO($str, $key)
{
$keysize = mcrypt_get_key_size(MCRYPT_DES, MCRYPT_MODE_CBC);
$ivbytes = array(72, 163, 99, 62, 219, 111, 163, 114);
$iv = implode(array_map("chr", $ivbytes));
$k = mhash(MHASH_SHA1, $key);
$blocksize = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
$padsize = $blocksize - (strlen($str) % $blocksize);
$str .= str_repeat(chr($padsize), $padsize);
return base64_encode(mcrypt_encrypt(MCRYPT_DES, substr($k, 0, $keysize), $str, MCRYPT_MODE_CBC, $iv));
}