title: Delphi DEC Twofish Encryption and server-side decryption in PHP
body: <p>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.</p>
  
  <p>I am using DEC 5.2 for Delphi.</p>
  
  <p>Here is the Delphi code that does the encryption:</p>
  
  <pre><code>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;
  </code></pre>
  
  <p>And PHP function that is supposed to decrypt sent data:</p>
  
  <pre><code>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;
  }
  </code></pre>
  
  <p>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.</p>