3

我几乎失去了我的头发,头脑和其他一切!我一直在尝试将此 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/)。对于任何反馈,我们都表示感谢。

4

2 回答 2

0

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

于 2014-01-26T03:58:55.510 回答
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);

        }
于 2014-01-27T16:14:09.503 回答