问题描述
我一直在使用 Lazarus/FPC Blowfish 库来加密文件流,它对我来说效果很好。
现在我尝试调整库来加密和解密任意内存结构(记录,还有字符串),但遇到了几天无法解决的问题,所以请帮忙。
问题是长度正好是 Blowfish 块大小(8 字节)倍数的字符串被正确加密和解密。如果字符串没有在精确的 8 字节边界处结束,则超出边界的字符将被破坏。
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,Key);
CryptCheckEdit.Text := ContentsBuffer;
end;
在这里您可以看到正在发生的事情:
解决方法
已解决。问题是我不允许截断 TBFBlock。要使 Blowfish 解密工作,ContetLength 必须是 TBFBlock 大小的倍数。