我必须用Twofish/CBC算法在Delphi中加密字符串,将其发送到服务器并在那里解密。我已经测试了下面的代码,B64编码/解码过程可以工作,但我在密码加密/解密方面停滞不前。
我使用DEC5.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;
}
我认为我必须更多地处理salt和初始化向量,但我不知道如何处理。据我所知,KDFx()函数从用户密码和salt中生成了SHA1散列密码,但我在这一点上几乎陷入了困境。
KDFx是一种专有的不兼容密钥派生方法,来源于:"类函数TDECHash.KDFx//DEC自己的KDF,甚至更强"。您将使用DEC和PHP中的problens,并且应该使用其他库。例如,在http://www.delphipraxis.net/171047-dec-5-2-mit-vector-deccipher-umbau-von-dot-net-auf-delphi.html