An existing C# implementation encrypts a string by implementing RijndaelManaged()
as follows:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace sample
{
class Program
{
static void Main(string[] args)
{
var sKey = "ABCDEF0123456789ABCDEF0123456789";
var sData = "Some Data";
var bData = Encoding.ASCII.GetBytes(sData);
var oAes = new RijndaelManaged();
oAes.Key = Encoding.ASCII.GetBytes(sKey.Substring(0, 32));
oAes.IV = Encoding.ASCII.GetBytes(sKey.Substring(0, 16));
var bEncrypted = oAes.CreateEncryptor(oAes.Key, oAes.IV).TransformFinalBlock(bData, 0, bData.Length);
Console.WriteLine(Convert.ToBase64String(bEncrypted));
// Output: NXyPbSVtB5LomNcsPK7cgg==
}
}
}
A php implementation must produce the same result, given the same input, so that the two resulting strings may be compared.
All of the libraries that I have tried lack a method similar to TransformFinalBlock().
Unfortunately, the C# implementation cannot be changed - we have to find a working php implementation.
A similar php implementation (using the phpseclib/phpseclib library) follows:
<?php
function getBytes($s) {
$result = '';
for ($i = 0; $i < mb_strlen($s, 'ASCII'); $i++) {
$result .= ord($s[$i]);
}
return $result;
}
$sKey = "ABCDEF0123456789ABCDEF0123456789";
$sData = "Some Data";
$bData = getBytes($sData);
$bKey = getBytes(substr($sKey, 0, 32));
$bIV = getBytes(substr($sKey, 0, 16));
include 'vendor/autoload.php';
$oAes = new \phpseclib\Crypt\Rijndael(2); // MODE_CBC - Default for RijndaelManaged()
$oAes->setBlockLength(128); // Default for RijndaelManaged()
$oAes->setKey($bKey);
$oAes->setIV($bIV);
$bEncrypted = $oAes->encrypt($bData);
echo(base64_encode($bEncrypted));
// Output: HwznolyEl6472Hm0rbNzINEa6LUwo4O4UAWd90P9PUg=
How can the same result be achieved in php?