PHP mcrypt_encrypt to .NET

1.9k views Asked by At

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

There are 2 answers

0
Gaurav Joseph On

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

0
David Acero On

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

        }