Reputation: 133
I try to do encrypt (with MCRYPT_RIJNDAEL_128 Cipher CBC) in PHP and C#, but the output does not match.
key = '1234567812345678';
iv = '1234567812345678';
PHP:
function Encrypt($data, $key, $iv) {
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, base64_encode($data), MCRYPT_MODE_CBC, $iv));
}
C#:
public static string Encrypt(string plainText, string key, string iv)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(iv);
byte[] plainTextBytes = Encoding.ASCII.GetBytes(plainText);
byte[] keyBytes = Encoding.ASCII.GetBytes(key);
using (RijndaelManaged symmetricKey = new RijndaelManaged())
{
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.Zeros;
symmetricKey.KeySize = 128;
symmetricKey.BlockSize = 128;
using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes))
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
return Convert.ToBase64String(cipherTextBytes);
}
}
}
}
}
Help appreciated.
Upvotes: 0
Views: 309
Reputation: 540
I think your problems lies within your PHP code.
The mcrypt_encrypt
function expects the data (which needs to be encoded) to be in plaintext format, so you don't need an additional base64_encode
since you are working with strings. The same way you pass the key
and the iv
to the function, you should hand your data
variable to it. (untested)
function Encrypt($data, $key, $iv) {
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv));
}
Let me know your progress, so that I can help you with this in the future if anything doesn't work :)
Upvotes: 1