Mcrypt and base64 with PHP and c#

混江龙づ霸主 提交于 2019-11-30 09:28:20
StigM

C# does Rijndael padding by default and uses PKCS7.

This means you have to pad your PHP side as per PKCS7, code below should work:

function string_encrypt($string, $key) {

  $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
  $padding = $block - (strlen($string) % $block);
  $string .= str_repeat(chr($padding), $padding);

    $crypted_text = mcrypt_encrypt(
                            MCRYPT_RIJNDAEL_128, 
                            $key, 
                            $string, 
                            MCRYPT_MODE_ECB
                        );
    return base64_encode($crypted_text);
}

For further information, see the first answer here

I should add also, that if you want to change the C# side and not use padding, make the below modification instead and leave the PHP side alone:

static string Encrypt(string plainText, string key)
{
  string cipherText;
  var rijndael = new RijndaelManaged()
  {
    Key = Encoding.UTF8.GetBytes(key),
    Mode = CipherMode.ECB,
    BlockSize = 128,
    Padding = PaddingMode.Zeros,
  };
  ICryptoTransform encryptor = rijndael.CreateEncryptor(rijndael.Key, null);

  using (var memoryStream = new MemoryStream())
  {
    using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
    {
      using (var streamWriter = new StreamWriter(cryptoStream))
      {
        streamWriter.Write(plainText);
        streamWriter.Flush();
      }
      //cipherText = Convert.ToBase64String(Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(memoryStream.ToArray())));
      cipherText = Convert.ToBase64String(memoryStream.ToArray());
      //cryptoStream.FlushFinalBlock();
    }
  }
  return cipherText;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!