Question

I have the following Visual Basic .NET function that is used to encrypt a file. This function is from third party so I cannot alter the original code.

Dim bytes As Byte() = New UnicodeEncoding().GetBytes("12345678")
Dim fileStream1 As FileStream = New System.IO.FileStream(txtInput.Text, FileMode.Create)
Dim rijndaelManaged As RijndaelManaged = New RijndaelManaged
Dim cryptoStream1 As CryptoStream = New CryptoStream(fileStream1, rijndaelManaged.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write)
Dim fileStream2 As FileStream = New System.IO.FileStream(txtOutput.Text, FileMode.Open)

Dim BytesRead As Integer
Dim buffer(4096) As Byte

Do
   BytesRead = fileStream2.Read(buffer, 0, buffer.Length) 
   If BytesRead > 0 Then
      cryptoStream1.Write(buffer, 0, BytesRead)
   End If
Loop While BytesRead > 0

I need help creating a PHP to decrypt the above function. Currently I tried to decrypt using this function in PHP:

function decrypt($text) {
  $key = mb_convert_encoding("12345678","utf-16"); 
  $iv = mb_convert_encoding("12345678","utf-16");

  return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, $iv), "\0");
}

$decrypted=decrypt(file_get_contents("tes_encrypted.xml"));

$nfile = fopen("test.xml", 'w');
fwrite($nfile, $decrypted);
fclose($nfile);

As you can see the encryption function in VB.NET use a predefined Key and IV. It also doesn't specify a padding method. The PHP function generates different result.

Was it helpful?

Solution

Finally I got the answer. Here the correct PHP code to decrypt the VB.NET encryption above:

function unpad($value)
{
    $blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $packing = ord($value[strlen($value) - 1]);
    if($packing && $packing < $blockSize)
    {
        for($P = strlen($value) - 1; $P >= strlen($value) - $packing; $P--)
        {
            if(ord($value{$P}) != $packing)
            {
                $packing = 0;
            }
        }
    }

    return substr($value, 0, strlen($value) - $packing); 
}


function decrypt($text) {
    $key= mb_convert_encoding("12345678","ucs-2LE");
    $iv= mb_convert_encoding("12345678","ucs-2LE");
    return unpad(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, $iv));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top