how to sync encryption between delphi and php using dcpcrypt

前端 未结 3 598
悲&欢浪女
悲&欢浪女 2020-12-30 18:21

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 en

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-30 18:45

    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:

    function EncryptStringDES: string;
    var
      des: TDCP_des;
      src, enc, b64: TBytes;
      index, slen, bsize, padsize: integer;
    begin
      des:=tdcp_des.Create(nil);
      try
        des.InitStr(AnsiString('test'), tdcp_sha1);
    
        src := TEncoding.UTF8.GetBytes('this is a test');
        slen := Length(src);
        // Add padding
        bsize := des.BlockSize div 8;
        padsize := bsize - (slen mod bsize);
        Inc(slen, padsize);
        SetLength(src, slen);
        for index := padsize downto 1 do
        begin
          src[slen - index] := padsize;
        end;
    
        SetLength(enc, slen);
        des.EncryptCBC(src[0], enc[0], slen);
        result := EncdDecd.EncodeBase64(@enc[0], Length(enc));
      finally
        des.Free;
      end;
    end;
    
    function DecryptStringDES(ASource: string): string;
    var
      des: TDCP_des;
      key, src, dec, b64: TBytes;
      pad, slen: integer;
    begin
      des := TDCP_des.Create(nil);
      try
        des.InitStr(AnsiString('test'), tdcp_sha1);
    
        src := EncdDecd.DecodeBase64(AnsiString(ASource));
        slen := Length(src);
        SetLength(dec, slen);
        des.DecryptCBC(src[0], dec[0], slen);
    
        // Remove padding
        pad := dec[slen - 1];
        SetLength(dec, slen - pad);
    
        result := TEncoding.UTF8.GetString(dec);
      finally
        des.Free;
      end;
    end;
    

    and the PHP:

    
    

提交回复
热议问题