0
我必須使用Twofish/CBC算法在Delphi中加密字符串,將其發送到服務器並在那裏解密。我已經測試了下面的代碼,並且B64編碼/解碼過程起作用,但是我被困在密碼加密/解密中。德爾福DEC Twofish加密和PHP中的服務器端解密
我對德爾福使用DEC 5.2。
這裏是德爾福代碼,不會加密:
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;
}
我beleive我不得不擺弄一點鹽和初始化向量,但我不知道如何。據我所知,KDFx()函數使得SHA1從用戶密碼和鹽中散列出密碼,但我幾乎堅持在這一點上。