c# - Is it possible to run a PHP function in .NET?

I'm trying to decrypt AES-128 CBC strings in C# but with no success (tried every decrypt method I found on internet for this type of encryption).

The only way I got a result was decrypting those strings in PHP using this code:

<?php
$crypto_data = hex2bin($crypto_data_hex);
$real_data = openssl_decrypt($crypto_data,
                                    'AES-128-CBC',
                                    '23d854ce7364b4f7',
                                    OPENSSL_RAW_DATA,
                                    '23d854ce7364b4f7');
?>

So, is there a way to run this PHP code in .NET (using a PHP.dll library or something similar) ? Or is there a real equivalent method for this operation in .NET C# ?

Thank you

Answer

Solution:

The question seems to boil down to writing C# function that is equivalent to PHP function.

Try this code:

public class Program
{
    public static byte[] HexToBytes(string hex)
    {
        int numberChars = hex.Length;
        byte[] bytes = new byte[numberChars / 2];
        for (int i = 0; i < numberChars; i += 2)
        {
            bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
        }

        return bytes;
    }

    static string Decrypt(byte[] cipherText, byte[] key, byte[] iv)
    {
        string plaintext;
        
        AesManaged aes = new AesManaged
        {
            Mode = CipherMode.CBC,
            Padding = PaddingMode.PKCS7,
            BlockSize = 128,
            Key = key,
            IV = iv
        };

        using (aes)
        {
            ICryptoTransform decryptor = aes.CreateDecryptor();
            using (MemoryStream ms = new MemoryStream(cipherText))
            {
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader reader = new StreamReader(cs))
                    {
                        plaintext = reader.ReadToEnd();
                    }
                }
            }
        }

        return plaintext;
    }

    public static void Main()
    {
        string crypto_data_hex = "00965fa56e761b11d37b887f98e6bcc2"; // paste $crypto_data_hex value here

        string sKey = "23d854ce7364b4f7";
        string sIv  = "23d854ce7364b4f7";

        byte[] encrypted = HexToBytes(crypto_data_hex);
        byte[] key = Encoding.ASCII.GetBytes(sKey);
        byte[] iv = Encoding.ASCII.GetBytes(sIv);
        
        string decrypted = Decrypt(encrypted, key, iv);
        Console.WriteLine(decrypted);
    }
}

Source