Different RC2 encryption results between C# and PHP

260 Views Asked by At

I'm trying to achieve the same result I reach with a C# code, using PHP. The encryption algorithm is RC2, using RC2CryptoServiceProvider for .NET and mcrypt() for PHP.

This is the C# part:

public static string encryptRC2(string datastring, string keystring, string ivstring)
{
    byte[] bytes = Encoding.UTF8.GetBytes(datastring);
    byte[] rgbKey = Encoding.ASCII.GetBytes(keystring);
    byte[] rgbIV = Encoding.ASCII.GetBytes(ivstring);
    MemoryStream stream = new MemoryStream();
    RC2CryptoServiceProvider provider = new RC2CryptoServiceProvider
    {
        KeySize = 0x40,
        BlockSize = 0x40
    };
    CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
    stream2.Write(bytes, 0, bytes.Length);
    stream2.FlushFinalBlock();
    return Convert.ToBase64String(stream.ToArray());
}

This is the PHP part:

function encryptRC2($datastring, $keystring, $ivstring) {
    $encrypted = mcrypt_encrypt(MCRYPT_RC2, $keystring, $datastring, MCRYPT_MODE_CBC, $ivstring);
    return base64_encode($encrypted);
}

I've tried to:

  • Force encoding with mb_convert_string() matching the C# side
  • Changing the cipher mode (even if default for C# is CBC, no way)
  • Try to base64_encode() an strtoupper() string

I can't change the C# algorithm, I need to match the same result with PHP.

0

There are 0 best solutions below