将PHP加密算法转换为C#

时间:2017-03-21 17:04:08

标签: c# encryption mcrypt rijndael rijndaelmanaged

我正在尝试在C#中使用SSO解决方案,其中文档仅在PHP中提供。

我有这个PHP代码:

function encrypt ($message)
{
    $initialVector = "1234567890123456";

    $key = md5($this->apiPassword);
    $crypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $message, MCRYPT_MODE_CFB, $initialVector);

    return base64_encode($initialVector) .":" . base64_encode($crypt);
}

我尝试过的C#代码如下:

private string encrypt(string message)
{
  RijndaelManaged aes128 = new RijndaelManaged();
  aes128.BlockSize = 128;
  aes128.KeySize = 128;
  aes128.Mode = CipherMode.CFB;
  aes128.Padding = PaddingMode.None;
  aes128.IV = Encoding.ASCII.GetBytes("1234567890123456");
  aes128.Key = Encoding.ASCII.GetBytes(getMd5(key));

  byte[] plainTextBytes = Encoding.ASCII.GetBytes(json);

  ICryptoTransform encryptor = aes128.CreateEncryptor();
  MemoryStream ms = new MemoryStream();

  CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
  cs.Write(plainTextBytes, 0, plainTextBytes.Length);

  // convert our encrypted data from a memory stream into a byte array.
  byte[] cypherTextBytes = ms.ToArray();

  // close memory stream
  ms.Close();

  return Convert.ToBase64String(aes128.IV) + ":" + Convert.ToBase64String(cypherTextBytes);
}

keymessage完全相同。 IV部分正确返回,只有加密部分不相等。 md5方法也正常工作。

编辑:更改填充内容也不会改变任何内容。

0 个答案:

没有答案