Using: Delphi 7, DEC v5.2
Please refer to this question: Delphi 7 - DCPCrypt - TDCP_rijndael - DecryptString - How to make it work?
From @AmigoJack's excellent answer, I have the Delphi Decrypt
function working fine. Based on that, I am now trying to implement the Encrypt
function but have been unsuccessful so far. What is happening is that the encryption is done in Delphi, and the string when decrypted in PHP is producing a different string than what was encrypted, implying that something is wrong in the Delphi code.
This is the code:
uses SysUtils, Windows, Classes, DECCipher, DECFmt, DecUtil;
function Encrypt(AStr: string): string;
function Decrypt(AStr: string): string;
implementation
const
GLUE = '::';
cPASSWORD = 'myownpassword';
function Encrypt(AStr: string): string;
var
c: TDecCipher;
sKey,
sIv,
sEncrypted,
sPlain: AnsiString;
iPosGlue,
iLength: Integer;
begin
sKey := cPASSWORD;
iLength := 16;
SetLength(sIv, iLength);
// Expect DEC 5.2 to only deal with AES-128-CBC, not 256.
c := ValidCipher(DecCipher.TCipher_Rijndael).Create;
try
c.Mode := cmCBCx;
c.Init(sKey, sIv); // Provide binary key and binary IV
sPlain := AStr;
iLength := Length(sPlain);
SetLength(sEncrypted, iLength); // By now the output length must match the input's
c.Encode(sPlain[1], sEncrypted[1], iLength);
finally
c.Free;
end;
Result := TFormat_MIME64.Encode(sEncrypted) + GLUE + TFormat_MIME64.Encode(sIv) + GLUE + IntToStr(iLength);
end;
I am sure that there is something missing with initialization of the variable Iv
, and would really be glad if someone could point out the mistake.
UPDATE:
As a first step, I've completed the implementation for Encrypt and have it working in Delphi (see my answer below). With that, I seem to have found a completely different, unrelated bug in the code, that I will post in a separate question.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…