Delphi で Twofish/CBC アルゴリズムを使用して文字列を暗号化し、サーバーに送信してそこで復号化する必要があります。以下のコードをテストしましたが、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 ハッシュ化されたパスワードを作成しますが、その時点でほとんど立ち往生しています。