AES使用DCrypt在Delphi(10 Seattle)中加密字符串,使用PHP / OpenSSL解密

时间:2016-12-22 14:42:05

标签: delphi encryption openssl aes

使用DCrypt在Delphi中给出这段代码:

Uses DCPcrypt2, DCPblockciphers, DCPrijndael, DCPbase64;

procedure TForm1.Button1Click(Sender: TObject);
var Cipher : TDCP_rijndael;
    ss, k, Data, Key, IV : Ansistring;
const
  KeySize = 32; // 32 bytes = 256 bits
  BlockSize = 16; // 16 bytes = 128 bits // IV
begin
  key := '12345678901234567890123456789012';
  iv  := '1234567890123456';
  Data := 'thisis128bitstxt';

  Cipher := TDCP_rijndael.Create(nil);
  Cipher.Init(Key[1],128,@IV[1]);
  Cipher.EncryptCBC(Data[1],Data[1],Length(Data));
  Cipher.Free;

  Data := DCPBase64.Base64EncodeStr(Data);
  Memo1.Lines.Add(Data);
end;

我得到以下内容: Eq7iMlVKysMMXdhR0rtrwA ==

在PHP中使用OpenSSL尝试相同的操作:

<?
    $s = "thisis128bitstxt";
    $s = openssl_encrypt($s, "AES-128-CBC", "12345678901234567890123456789012", 0, "1234567890123456");
    echo $s . "</br>";
?>

返回:Eq7iMlVKysMMXdhR0rtrwEbhkypNJyuwGafLILvwpbY =

怎么了?

如果我尝试解密delphi输出,我会得到一个空字符串:

$s = "Eq7iMlVKysMMXdhR0rtrwA==";
$s = openssl_decrypt($s, "AES-128-CBC", "12345678901234567890123456789012", 0, "1234567890123456");
echo $s . "</br>";

1 个答案:

答案 0 :(得分:5)

David Heffernan已经指导你朝着正确的方向前进。 我在这里完成它。

你不应该错过填充。 我修改了你的代码如下。

procedure TForm1.Button1Click(Sender: TObject);
var Cipher : TDCP_rijndael;
    Data, Key, IV : ansistring;
    index, dataLength, bsize, pad: integer;
begin
  key := '12345678901234567890123456789012';
  IV  := '1234567890123456';
  Data := 'thisis128bitstxt';

  Cipher := TDCP_rijndael.Create(nil);
  try
    Cipher.Init(Key[1],128,@IV[1]);

    //don't miss padding
    {start padding}
    dataLength := Length(Data);
    bsize := (Cipher.BlockSize div 8);
    pad := bsize - (dataLength mod bsize);
    for index := 1 to pad do
      Data := Data+chr(pad);
    {end padding}

    Cipher.EncryptCBC(Data[1],Data[1],Length(Data));
  finally
    Cipher.Free;
  end;

  Data := DCPBase64.Base64EncodeStr(Data);
  Memo1.Lines.Add(Data);
end;

你现在可以得到与php相同的结果。