duankan8739 2013-09-08 07:33
浏览 47

PHP mcrypt_encrypt到.NET

I have almost lost my hair, mind and everything else! I have been trying to convert this PHP function to 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:

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. (http://writecodeonline.com/php/). Any feedback would be appreciated.

  • 写回答

2条回答 默认 最新

  • duanmiyang6201 2014-01-26 03:58
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)