PHP mcrypt_encrypt到.NET

时间:2013-09-08 07:33:17

标签: c# php rijndaelmanaged

我几乎失去了我的头发,头脑和其他一切!我一直在尝试将这个PHP函数转换为C#:

function  encrypt_decrypt($action, $string) {
  $output = false;
  $key = 'My strong secret key';
  // initialization vector
  $iv = md5(md5($key));
  $output = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, $iv);
  $output = bin2hex($output);
  return $output;
}

我一直在与Rijandel班级合作:

function  encrypt_decrypt(string password) {
  UTF8Encoding encoding = new UTF8Encoding();
  // For consistency with PHP function, MD5Encrypt applies MD5 encryption and does a bin2hex
  byte[] Key = Encoding.ASCII.GetBytes(MD5Encrypt(password).ToLower());
  byte[] IV = Encoding.ASCII.GetBytes(MD5Encrypt(MD5Encrypt(password).ToLower()).ToLower());

  RijndaelManaged rj = new RijndaelManaged();
  rj.BlockSize = 256;
  rj.KeySize = 256;
  rj.Key = Key;
  rj.IV = IV;
  rj.Mode = CipherMode.CBC;
  MemoryStream ms = new MemoryStream();

  using (CryptoStream cs = new CryptoStream(ms, rj.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
  {
    using (StreamWriter sw = new StreamWriter(cs))
    {
      sw.Write(message);
      sw.Close();
    }
    cs.Close();
  }
  byte[] encoded = ms.ToArray();                
  string output = "";
  foreach (var ele in encoded)
  {
    output += ele.ToString("X2");
  }

  return output;
}

我一直在用C#代码验证PHP代码的输出,但它们不匹配。 (http://writecodeonline.com/php/)。任何反馈都将不胜感激。

2 个答案:

答案 0 :(得分:0)

在执行此操作时需要记住多个问题,例如转换二进制文件,检查编码和填充问题。由于我们无法看到您的完整代码,因此在这种情况下我们无能为力。请查看本教程以获取更多信息:http://blog.djekldevelopments.co.uk/?p=334

答案 1 :(得分:0)

请改为尝试:

        using (RijndaelManaged myRijndael = new RijndaelManaged())
        {

            myRijndael.Key = Encoding.UTF8.GetBytes(password);
            string strIv16 = "\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0";
            myRijndael.IV = Encoding.UTF8.GetBytes(strIv16);

            // Encrypt the string to an array of bytes. 
            byte[] encrypted = EncryptStringToBytes(message, myRijndael.Key, myRijndael.IV);
            string output = Convert.ToBase64String(encrypted);

        }