MCRYPT Equivalence from C# to PHP (Rijndael)

Today I had an interesting case decrypting MCRYPT cipher from PHP using C# Rijndael implementation. There are some difference between the two implementations that make it confusing to get encryption working on both sides.

Here’s the alogrithm we came up with, this allow for encryption / decryption in PHP and also in C#.

 

PHP :

<?php

$iv = “45287112549354892144548565433341”;
$key1 = “SomePrivateKey!$@”;
$text1 = “This is my encrypted message”;

$result1 = encryptText($text1,$key1, $iv);
$result2 = decryptText($result1,$key1, $iv);

print($result1) . “\n<br/>”;
print($result2) . “\n<br/>”;

function encryptText($text, $key, $iv)
{
$iv = “45287112549354892144548565456541”;
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$padding = $block – (strlen($text) % $block);
$text .= str_repeat(chr($padding), $padding);

$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);

return base64_encode($crypttext);
}
function decryptText($text, $key)
{
$text = base64_decode($text);

$iv = “45287112549354892144548565456541”;

$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);
return $decrypttext;
}
?>

C#

public static void Foo()
{
var iv = “45287112549354892144548565433341”;
var key = “SomePrivateKey!$@”;
var cypher = “cwQjhtHoPdxaenYXmvnek/l7q5T3g/cZ4BYlrIcdQFc=”;

var result = DecryptRJ256(Decode(cypher),key,iv);
}

public static byte[] Decode(string str)
{
var decbuff = Convert.FromBase64String(str);
return decbuff;
}

static public String DecryptRJ256(byte[] cypher, string KeyString, string IVString)
{
var sRet = “”;

while (KeyString.Length < 16)
{
KeyString += “\0”;
}

var encoding = new UTF8Encoding();
var Key = encoding.GetBytes(KeyString);
var IV = encoding.GetBytes(IVString);

using (var rj = new RijndaelManaged())
{
try
{
rj.Padding = PaddingMode.PKCS7;
rj.Mode = CipherMode.CBC;
rj.KeySize = 256;
rj.BlockSize = 256;
rj.Key = Key;
rj.IV = IV;
var ms = new MemoryStream(cypher);

using (var cs = new CryptoStream(ms, rj.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
{
using (var sr = new StreamReader(cs))
{
sRet = sr.ReadLine();
}
}
}
finally
{
rj.Clear();
}
}

return sRet;
}

Submit a Comment

Your email address will not be published. Required fields are marked *

Share This