I have to encrypt string in Delphi with Twofish/CBC algorithm, send it to server and decrypt there. I've tested the code below, and B64 encoding/decoding process works, however I'm stuck at cipher encryption/decryption.
I am using DEC 5.2 for Delphi.
Here is the Delphi code that does the encryption:
class function TEncryption.EncryptStream(const AInStream: TStream; const AOutStream: TStream; const APassword: String): Boolean;
var
ASalt: Binary;
AData: Binary;
APass: Binary;
begin
with ValidCipher(TCipher_Twofish).Create, Context do
try
ASalt := RandomBinary(16);
APass := ValidHash(THash_SHA1).KDFx(Binary(APassword), ASalt, KeySize);
Mode := cmCBCx;
Init(APass);
EncodeStream(AInStream, AOutStream, AInStream.Size);
result := TRUE;
finally
Free;
ProtectBinary(ASalt);
ProtectBinary(AData);
ProtectBinary(APass);
end;
end;
class function TEncryption.EncryptString(const AString, APassword: String): String;
var
instream, outstream: TStringStream;
begin
result := '';
instream := TStringStream.Create(AString);
try
outstream := TStringStream.Create;
try
if EncryptStream(instream, outstream, APassword) then
result := outstream.DataString;
finally
outstream.Free;
end;
finally
instream.Free;
end;
end;
And PHP function that is supposed to decrypt sent data:
function decrypt($input, $key) {
$td = mcrypt_module_open('twofish', '', 'cbc', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$decrypted_data = mdecrypt_generic($td, base64_decode_urlsafe($input));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $decrypted_data;
}
I beleive I have to fiddle a bit more with salt and initialization vectors, however I have no idea how. From what I understand, KDFx() function makes SHA1 hashed password out from user password and salt, but I'm pretty much stuck at that point.
KDFx is an proprietary incompatible key derivation method, from the source: "class function TDECHash.KDFx // DEC's own KDF, even stronger". You will have problens using this from DEC and PHP and should use other libraries. The problem is discussed e.g. in http://www.delphipraxis.net/171047-dec-5-2-mit-vector-deccipher-umbau-von-dot-net-auf-delphi.html