I'm using Delphi 2009 and most of the answers I've seen here are for 2010+ I am trying to sync encryption (delphi) to decryption (php) and failing.
generate the encrypted string in delphi:
program Project4;
{$APPTYPE CONSOLE}
uses
SysUtils,
DCPcrypt2,
DCPsha1,
DCPblockciphers,
DCPdes,
EncdDecd;
var des: tdcp_des;
enc,dec: ansistring;
begin
try
des:=tdcp_des.Create(nil);
des.InitStr('test', tdcp_sha1);
enc:=encodestring(des.EncryptString('this is a test'));
des.Free;
des:=tdcp_des.Create(nil);
des.InitStr('test', tdcp_sha1);
dec:=des.DecryptString(decodestring(enc));
des.Free;
writeln(enc);
writeln(dec);
except
on E:Exception do
Writeln(E.Classname, ': ', E.Message);
end;
end.
decrypt in php:
<?php
function decrypt($str, $key)
{
$size = mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
$data = base64_decode($str);
$block = mcrypt_get_block_size('des', 'ecb');
$k = substr(sha1($key), 0, $block);
$str = mcrypt_decrypt(MCRYPT_DES, $k, $data, MCRYPT_MODE_CBC, $iv);
$pad = ord($str[($len = strlen($str)) - 1]);
return substr($str, 0, strlen($str) - $pad);
}
$enc = 'TW5mbVFhODUyR2FoOTA2WWJIOD0=';
$dec = decrypt($enc, 'test');
echo "$dec\n";
?>
Several issues, I think :-)
des.InitStr() internally creates an IV from 8 null bytes which it then encrypts. You need to use the same IV in your PHP.
The sha1($key) produces a hex string rather than the actual bytes of the password. You need something like mhash instead.
I couldn't manage to reproduce your $enc string with the given Delphi function.
Unicode issues - the password and source text are going to be treated as unicode in Delphi.
You seem to be base 64 encoding the source twice in the Delphi routines. des.EncryptString and des.DecryptString produce and consume base 64 encoded strings so no need to do it again.
Padding
Based on my previous answer here - this is my suggestion:
and the PHP:
i use this kind of integration with success but i cant provide more information than that, it belongs to my employer.
did you initialized mycrypt?
dont forget to encode your string properly in delphi, i use Base64EncodeStr(Buffer);
i hope it helps.
who is the iv bytes
for the key: test123456