Php Decrypt from C# .NET RIJNDAEL 256

by Dani Arlandis — on

Sometimes we need communicate two sites that are implemented with diferents languages. In these case we get a encripted data under C# and will decript them with PHP

The C# function for encrypt data

---
internal const string iv_to_pass_to_decryption = "YOURPHASPHRASE";
private string encryptData(string data)
{
    Rijndael rin = Rijndael.Create();
    rin.KeySize = 256;
    rin.BlockSize = 256;
    rin.Mode = CipherMode.CBC;
    rin.Padding = PaddingMode.PKCS7;
    rin.Key = Convert.FromBase64String(iv_to_pass_to_decryption);

    ICryptoTransform crypto = aes.CreateEncryptor(rin.Key, rin.IV);
    byte[] txt = ASCIIEncoding.UTF8.GetBytes(data);          
    byte[] cipherText = crypto.TransformFinalBlock(txt, 0, txt.Length);

    return "&data=" + Convert.ToBase64String(cipherText) + "&iv=" + Convert.ToBase64String(rin.IV);
}
---

Usage

EncryptRijndael('STRINGTOECRYPT');

The PHP function for decrypt data

Class DecryptClass {
    private $iv_to_pass_to_decryption = 'YOURPHASPHRASE';
    public function decrypt($data,$iv)
    {
        $data = base64_decode(str_replace(' ', '+', $data));
        $iv = base64_decode(str_replace(' ', '+', $iv));
        return mcrypt_decrypt(MCRYPT_RIJNDAEL_256, base64_decode($this->iv_to_pass_to_decryption), $data, MCRYPT_MODE_CBC, $iv);
    }
}

Usage

$rn = new DecryptClass()
$rn->decrypt($data,$iv);

Tip: $data and $iv is GET or POST params generated in C#