I came across this thread while googling. However after trying it out and making adjustments, I've come across a hurdle, hopefully someone can help me out a bit.
The code above is fine but since the algorithm isn't really useful without making the IV change everytime, I tried using following code to generate iv but it kept saying "Specified key is not a valid size for this algorithm." in my C# debugger.
I also tried outputting IV from the C# code, after decoding base 64 string the string length varies from 30 31 2X ==> basically just fluctuates for some reason.
I also would like to change the KEY as well but couldn't due to similar reasons as the IV issue, so hopefully someone can help me out with that?
(I've tried the following from http://php.net/manual/en/function.mcrypt-encrypt.php, couldn't get it to work in harmony with C#, maybe once I fix the IV issue I'll be able to fix this as well?
$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3"); )
PHP========================
<?php
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
//$iv = "45287112549354892144548565456541";
$key = "anjueolkdiwpoida";
$text = "This is my encrypted message";
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);
$crypttext = urlencode($crypttext);
$crypttext64=base64_encode($crypttext);
print($crypttext64) . "\n<br/>";
print(base64encode($iv)) . "\n<br/>";
?>
C#========================
string iv = Encoding.UTF8.GetString(Convert.FromBase64String("SOME IV STRING I COPY FROM BROSWER WITH ABOVE PHP LOADED"));
string kyy = "anjueolkdiwpoida";
//ciphertext is also SOME TXT STRING I COPIED FROM BROWSER WITH ABOVE PHP LOADED
string plainText = ValidationControls.DecryptRJ256(cipherText, kyy, iv);
public byte[] Decode(string str)
{
var decbuff = Convert.FromBase64String(str);
return decbuff;
}
static public String DecryptRJ256(byte[] cypher, string KeyString, string IVString)
{
var sRet = "";
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();
}
}
}
catch (Exception exc) { Console.WriteLine(exc.Message); App.Current.Shutdown(); }
finally
{
rj.Clear();
}
}
return sRet;
}