1

如何检测解密失败?我有以下测试代码:

procedure TForm1.Button1Click(Sender: TObject);
var 
 plainms, cipherms: TMemoryStream;
 tempstr: string;

begin
  plainms := TMemoryStream.Create;
  cipherms := TMemoryStream.Create;
  try
    cipherms.LoadFromFile('rwcx.ini');
    Codec1.Password := '122rkdkdk';  
    try
     Codec1.DecryptStream(plainms, cipherms);
    except on E: Exception do
      showmessage(e.Message);
    end;
    plainms.Position := 0;
    SetLength(tempstr, plainms.Size * 2);
    BinToHex(plainms.Memory, PChar(tempstr), plainms.Size);
    showmessage(tempstr);
  finally
    plainms.Free;
    cipherms.Free;
  end;
end;

文件“rwcx.ini”只是一个纯文本文件,包含加密数据。我正在使用带有 CBC 的 AES 256 和安装了“GetIt”的密码箱 3.5 版。我希望 plainms 内存流为空或引发异常,因为解密肯定会失败。相反,我得到了普通的垃圾,也不例外。

你如何检测解密失败?我必须能够检测到错误的密码或损坏的输入数据。我错过了什么?

4

1 回答 1

2

加密只是一种变换,它本身并没有正确解密的概念。

一种方法是创建加密数据的 HMAC 并将其添加到加密数据中,并在解密 HMAC 时加密数据并比较 HMAC。小心使用 HMAC 比较函数,它需要相同的时间来匹配和不匹配的值。

于 2016-02-12T12:34:04.823 回答