【发布时间】:2012-06-25 18:56:33
【问题描述】:
我正在尝试将 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 版本需要一个字符串来表示 $key 和 $iv 值,而 C# 版本需要一个字节数组。
如何修改我的 PHP 函数以模仿 C# 函数?
[edit] c# 函数是第 3 方,我无权更改它;我需要在 PHP 中编写等效的代码来以相同的方式对给定的字符串进行编码
【问题讨论】:
-
我不知道 Rijndael 的函数是如何工作的,但是你的 PHP 版本中
1的数量比你的 . NET 版本? -
try { ... } catch { throw; }只是代码污染。 -
谢谢,我实际上查看了一些类似的帖子。我认为我的问题更多地与 2 个函数之间的密钥/iv 格式有关,而不是加密本身。由于 PHP 没有字节类型,如何将 c# 中的字节数组转换为 PHP 中的 $key128 和 $iv 变量?
标签: c# php encryption