你好
<?php
$string = "Some text to be encrypted";
$secret_key = "51f732e39e5d800569802df7c37631f4";
$iv = "0123456789abcdef";
$encrypted_string = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $secret_key, $string, MCRYPT_MODE_CBC, $iv);
$decrypted_string = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $secret_key, $encrypted_string, MCRYPT_MODE_CBC, $iv);
echo "Original string : " . $string . "<br />\n";
echo "Encrypted string : " . $encrypted_string . "<br />\n";
echo "Decrypted string : " . $decrypted_string . "<br />\n";
echo "----<br />\n";
echo "IV " . $iv . "<br />\n";
echo "IV " . base64_encode($iv) . "<br />\n";
echo "Encrypted string : " . base64_encode($encrypted_string) . "<br />\n";
?>
结果: ... 加密字符串:r+zYEk/vwa9kjJ62Y4e0X9WK2uUhMEjPTeeLy7E/UgU=
在delphi中尝试使用免费库CryptoBlackBox
const
iviv: RawByteString = '0123456789abcdef';
keykey: RawByteString = '51f732e39e5d800569802df7c37631f4';
procedure TForm1.sButton1Click(Sender: TObject);
var
Crypto : TElSymmetricCrypto;
KeyMaterial : TElSymmetricKeyMaterial;
Factory : TElSymmetricCryptoFactory;
Secret: ByteArray;
IV: ByteArray;
Data: RawByteString;
Input, Output: ByteArray;
Result: AnsiString;
OutSize: Integer;
begin
Factory := TElSymmetricCryptoFactory.Create;
SetLength(Secret, Length(keykey));
Move(keykey[1], Secret[0], Length(keykey));
SetLength(IV, Length(iviv));
Move(iviv[1], IV[0], Length(iviv));
KeyMaterial:= TElSymmetricKeyMaterial.Create;
KeyMaterial.Key:= Secret;
KeyMaterial.IV:= IV;
ShowMessage('IV Length: ' + length(KeyMaterial.IV).ToString);
Crypto := Factory.CreateInstance(SB_ALGORITHM_CNT_AES256, cmCBC);
Crypto.KeyMaterial:= KeyMaterial;
Data:= DecodeBase64(sEdit2.Text);
SetLength(Input, Length(Data));
Move(Data[1], Input[0], Length(Data));
ShowMessage('Input Length: ' + length(Input).ToString);
try
OutSize := 0;
Crypto.Decrypt(@Input[0], Length(Input), nil, OutSize);
ShowMessage('Length: ' + IntToStr(OutSize));
SetLength(Output, OutSize);
Crypto.Decrypt(@Input[0], Length(Input), @Output[0], OutSize);
SetLength(Output, OutSize);
SetLength(Result, OutSize);
Move(Output[0], Result[1], OutSize);
ShowMessage(Result);
except
on E: Exception do
ShowMessage(E.Message);
end;
end;
结果 - 异常:
First chance exception at $77511D4D. Exception class EElSymmetricCryptoError with message 'Invalid symmetric cipher padding'.
可能遇到过这样的人吗?就像所有一样 - key 和初始化向量,准确解密所需的数据。
最佳答案
MCRYPT_RIJNDAEL_256
不是 AES,它是 block 大小为 256 位的 Rijndael 密码,而不是 key 大小为 256 的 AES。使用 MCRYPT_RIJNDAEL_128
使用正确大小的键。
还要确保您的字符编码和填充模式匹配。我找不到您的 Delphi 代码的填充机制,PHP 使用零字节填充到 block 边界(0..15 字节)。
关于php - Delphi CryptoBlackBox 和 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25223344/