I'm unable to make the C# RijndaelManaged encryption work with PHP mcrypt_encrypt as I kept getting "Specified key is not a valid size for this algorithm".
The PHP specification use 256 bit, with ECB cipher mode. My understanding is Initization Vector is not used when in ECB mode.
We're using temporary key to get this working in development project, to keep on building the developmental application and we'll issue a new secure key much later.
[PHP]
$plaintext = '1~ABCDEFG~1408740350~0~';
for($i = 1; $i <= 32; $i++) { $key .= chr($i); }
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $plaintext, 'ecb', '');
[C#]
string postFormData = "1~ABCDEFG~1408740350~0~";
StringBuilder sb = new StringBuilder();
foreach (var b in Encoding.ASCII.GetBytes(String.Concat(Enumerable.Range(1, 32)))) { sb.AppendFormat("{0}", b); }
postedFormData = RijndaelAES.Encrypt(postedFormData, sb.ToString());
public static string Encrypt(string plainText, string key)
{
string cipherText;
var rijndael = new RijndaelManaged()
{
Key = Encoding.UTF8.GetBytes(key),
Mode = CipherMode.ECB,
BlockSize = 256, //128,
Padding = PaddingMode.Zeros//,
//IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
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(memoryStream.ToArray());
}
}
return cipherText;
}