简体   繁体   English

PHP mcrypt_encrypt到.NET

[英]PHP mcrypt_encrypt to .NET

I have almost lost my hair, mind and everything else! 我几乎失去了我的头发,头脑和其他一切! I have been trying to convert this PHP function to C#: 我一直在尝试将此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;
}

I have been working with Rijandel Class: 我一直在与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;
}

I have been validating the output of the PHP code with that from the C# code and they do not match. 我一直在用C#代码验证PHP代码的输出,但它们不匹配。 ( http://writecodeonline.com/php/ ). http://writecodeonline.com/php/ )。 Any feedback would be appreciated. 对于任何反馈,我们都表示感谢。

There are multiple issues to be kept in mind while doing this like converting binary, checking encoding and padding issues. 在执行此操作时需要记住多个问题,例如转换二进制文件,检查编码和填充问题。 Since we cannot see your complete code we are helpless in this case. 由于我们无法看到您的完整代码,因此在这种情况下我们无能为力。 Check this tutorial for further info: http://blog.djekldevelopments.co.uk/?p=334 查看本教程以获取更多信息: http//blog.djekldevelopments.co.uk/?p = 334

Try this instead: 试试这个:

        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);

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM