首页 > 解决方案 > 我需要帮助解决 Lazarus FPC Blowfish 库使用问题

问题描述

我一直在使用 Lazarus/FPC Blowfish 库来加密文件流,它对我来说效果很好。

现在我尝试调整库以加密和解密任意内存结构(记录,还有字符串),但遇到了一个我无法在几天内解决的问题,所以请帮忙。

问题是长度是 Blowfish 块大小(8 字节)的精确倍数的字符串被正确加密和解​​密。如果一个字符串没有以精确的 8 字节边界结束,超出边界的字符将被破坏。

这是代码(完整的 Lazarus 项目请点击链接)

链接到 Lazarus 项目 zip

Procedure BlowfishEncrypt(var Contents;ContentsLength:Integer;var Key:String);

// chop Contents into 64 bit blocks and encrypt using key

var
  arrShadowContent:Array of Byte absolute Contents;
  objBlowfish: TBlowFish;
  BlowfishBlock: TBFBlock;
  ptrBlowfishKey:PBlowFishKey;
  p1,count,maxP:integer;

begin
  ptrBlowfishKey := addr(Key[1]);
  objBlowfish := TBlowFish.Create(ptrBlowfishKey^,Length(Key));
  p1 := 0;
  maxP := ContentsLength - 1;
  count := SizeOf(BlowfishBlock);
  while p1 < maxP do
     begin
     fillChar(BlowfishBlock,SizeOf(BlowfishBlock),0); // only for debugging
     if p1 + count > maxP then
        count := ContentsLength - p1;
     Move(arrShadowContent[p1],BlowfishBlock,count);
     objBlowfish.Encrypt(BlowfishBlock);
     Move(BlowfishBlock,arrShadowContent[p1],count);
     p1 := p1 + count;
     end;
  FreeAndNil(objBlowfish);
end;

这就是电话...

procedure TForm1.CryptButtonClick(Sender: TObject);

var
  ContentsBuffer,Key:String;

begin
ContentsBuffer := PlainTextEdit.Text;
Key := KeyTextEdit.Text;
BlowFishEncrypt(ContentsBuffer,Length(ContentsBuffer),Key);
CryptOutEdit.Text := ContentsBuffer;
BlowFishDecrypt(ContentsBuffer,Length(ContentsBuffer),Key);
CryptCheckEdit.Text := ContentsBuffer;
end; 

在这里你可以看到发生了什么:

测试界面截图

标签: lazarusblowfish

解决方案


解决。问题是我不允许截断 TBFBlock。要使 Blowfish 解密工作,ContetLength 必须是 TBFBlock 大小的倍数。


推荐阅读