我必须使用 Twofish/CBC 算法在 Delphi 中加密字符串,将其发送到服务器并在那里解密。我已经测试了下面的代码,并且 B64 编码/解码过程有效,但是我被困在密码加密/解密上。
我正在为 Delphi 使用 DEC 5.2。
这是进行加密的 Delphi 代码:
class function TEncryption.EncryptStream(const AInStream: TStream; const AOutStream: TStream; const APassword: String): Boolean;
var
ASalt: Binary;
AData: Binary;
APass: Binary;
begin
with ValidCipher(TCipher_Twofish).Create, Context do
try
ASalt := RandomBinary(16);
APass := ValidHash(THash_SHA1).KDFx(Binary(APassword), ASalt, KeySize);
Mode := cmCBCx;
Init(APass);
EncodeStream(AInStream, AOutStream, AInStream.Size);
result := TRUE;
finally
Free;
ProtectBinary(ASalt);
ProtectBinary(AData);
ProtectBinary(APass);
end;
end;
class function TEncryption.EncryptString(const AString, APassword: String): String;
var
instream, outstream: TStringStream;
begin
result := '';
instream := TStringStream.Create(AString);
try
outstream := TStringStream.Create;
try
if EncryptStream(instream, outstream, APassword) then
result := outstream.DataString;
finally
outstream.Free;
end;
finally
instream.Free;
end;
end;
以及应该解密发送数据的 PHP 函数:
function decrypt($input, $key) {
$td = mcrypt_module_open('twofish', '', 'cbc', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$decrypted_data = mdecrypt_generic($td, base64_decode_urlsafe($input));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $decrypted_data;
}
我相信我必须更多地使用盐和初始化向量,但是我不知道如何。据我了解,KDFx() 函数将 SHA1 哈希密码从用户密码和盐中提取出来,但我几乎被困在了这一点上。