我正在尝试将 C# 函数转换为 PHP。
这是 C# 函数:
public string Encrypt(string Value)
{
string RetVal = "";
if(Value != string.Empty && Value != null)
{
MemoryStream Buffer = new MemoryStream();
RijndaelManaged RijndaelManaged = new RijndaelManaged();
UnicodeEncoding UnicodeEncoder = new UnicodeEncoding();
byte[] KeyArray = new Byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
byte[] IVArray = new Byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
try
{
byte[] ValueBytes = UnicodeEncoder.GetBytes(Value);
CryptoStream EncryptStream = new CryptoStream(Buffer,
RijndaelManaged.CreateEncryptor(KeyArray, IVArray),
CryptoStreamMode.Write);
EncryptStream.Write(ValueBytes, 0, ValueBytes.Length);
EncryptStream.FlushFinalBlock();
// Base64 encode the encrypted data
RetVal = Convert.ToBase64String(Buffer.ToArray());
}
catch
{
throw;
}
}
return RetVal;
}
这是我在 PHP 中的尝试:
function EncryptString ($cleartext)
{
$cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
$key128 = '111111111111111111111111111';
$iv = '111111111111111111111111111';
if (mcrypt_generic_init($cipher, $key128, $iv) != -1) //Parameter iv will be ignored in ECB mode
{
$cipherText = mcrypt_generic($cipher,$cleartext );
mcrypt_generic_deinit($cipher);
$encrypted = (bin2hex($cipherText));
return base64_encode($encrypted);
}
}
目前,当我使用这两个函数对测试短语“test”进行编码时,我得到不同的值。看起来 PHP 版本需要一个字符串 for$key
和$iv
values,而 C# 版本需要一个字节数组。
如何修改我的 PHP 函数以模仿 C# 函数?
[编辑] c# 函数是第 3 方,我无权更改它;我需要在 PHP 中编写等效的代码来以相同的方式对给定的字符串进行编码