Почему эти два кода (php / C#) не шифруют / дешифруют одинаково? - PullRequest
1 голос
/ 20 апреля 2020

На веб-сайте 7.1 php эта функция шифрует строку, и я должен расшифровать ее в веб-службе C#, но они не дают такой же зашифрованный / расшифрованный результат. Есть ли какая-либо причина, по которой методы шифрования в php и c# не шифруются одинаково с одним и тем же секретным ключом и ключом iv? ...

В PHP зашифрованный вопрос: l0zhGwbpC3aQLaEuQAgmqL3gdWBPKhqjX7 / s5o / x2i6mPW74kSmsWMesweNHYfR1, в то время как в C# это дает такой результат: cWI7Ovb44gDl3WZ / p86JLjFdmAFml92VmbrwZnQZH9z + RMfGPx6hp2e6c * echo * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

"; echo"

        $output = openssl_decrypt(base64_decode($question), $encrypt_method, $key, 0, $iv);
";

?>

и C# код:

using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace ConsoleApp1
{
    class Program
    {
        static string EncryptString(string plainText, byte[] key, byte[] iv)
    {
        // Instantiate a new Aes object to perform string symmetric encryption
        Aes encryptor = Aes.Create();

        encryptor.Mode = CipherMode.CBC;

        // Set key and IV
        byte[] aesKey = new byte[32];
        Array.Copy(key, 0, aesKey, 0, 32);
        encryptor.Key = aesKey;
        encryptor.IV = iv;

        // Instantiate a new MemoryStream object to contain the encrypted bytes
        MemoryStream memoryStream = new MemoryStream();

        // Instantiate a new encryptor from our Aes object
        ICryptoTransform aesEncryptor = encryptor.CreateEncryptor();

        // Instantiate a new CryptoStream object to process the data and write it to the 
        // memory stream
        CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);

        // Convert the plainText string into a byte array
        byte[] plainBytes = Encoding.ASCII.GetBytes(plainText);

        // Encrypt the input plaintext string
        cryptoStream.Write(plainBytes, 0, plainBytes.Length);

        // Complete the encryption process
        cryptoStream.FlushFinalBlock();

        // Convert the encrypted data from a MemoryStream to a byte array
        byte[] cipherBytes = memoryStream.ToArray();

        // Close both the MemoryStream and the CryptoStream
        memoryStream.Close();
        cryptoStream.Close();

            // Convert the encrypted byte array to a base64 encoded string
            string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);

        // Return the encrypted data as a string
        return cipherText;
    }

        static string DecryptString(string cipherText, byte[] key, byte[] iv)
    {
        // Instantiate a new Aes object to perform string symmetric encryption
        Aes encryptor = Aes.Create();

        encryptor.Mode = CipherMode.CBC;

        // Set key and IV
        byte[] aesKey = new byte[32];
        Array.Copy(key, 0, aesKey, 0, 32);
        encryptor.Key = aesKey;
        encryptor.IV = iv;

        // Instantiate a new MemoryStream object to contain the encrypted bytes
        MemoryStream memoryStream = new MemoryStream();

        // Instantiate a new encryptor from our Aes object
        ICryptoTransform aesDecryptor = encryptor.CreateDecryptor();

        // Instantiate a new CryptoStream object to process the data and write it to the 
        // memory stream
        CryptoStream cryptoStream = new CryptoStream(memoryStream, aesDecryptor, CryptoStreamMode.Write);

        // Will contain decrypted plaintext
        string plainText = String.Empty;

        try
        {
            // Convert the ciphertext string into a byte array
            byte[] cipherBytes = Convert.FromBase64String(cipherText);

            // Decrypt the input ciphertext string
            cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);

            // Complete the decryption process
            cryptoStream.FlushFinalBlock();

            // Convert the decrypted data from a MemoryStream to a byte array
            byte[] plainBytes = memoryStream.ToArray();

            // Convert the decrypted byte array to string
            plainText = Encoding.ASCII.GetString(plainBytes, 0, plainBytes.Length);
        }
        finally
        {
            // Close both the MemoryStream and the CryptoStream
            memoryStream.Close();
            cryptoStream.Close();
        }

        // Return the decrypted data as a string
        return plainText;
    }
    static void Main(string[] args)
        {
            string message = "Quel est le nom de jeune fille de ma mère ?";
            string password = "Hakei54?sqSe6R71!lmdlrmPks65ekcj";
            string secretiv= "Ryfdhi.q546dmlfp";

            // Create sha256 hash
            SHA256 mySHA256 = SHA256.Create();
            byte[] key = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(password));
            byte[] iv = new byte[16] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
            Array.Copy(mySHA256.ComputeHash(Encoding.ASCII.GetBytes(secretiv)), 0, iv, 0, 16);


            // Create secret IV
            //Console.OutputEncoding = System.Text.Encoding.UTF8;

            Console.WriteLine("Hello World!");
            string encrypted = EncryptString(message, key, iv);
            string decrypted = DecryptString(encrypted, key, iv);

            Console.WriteLine(encrypted);
            Console.WriteLine(decrypted);
            Console.ReadKey();
        }
    }
}
...