ผลลัพธ์ที่แตกต่างกันเมื่อเข้ารหัสข้อมูลโดยใช้ AES-128-CBC ใน C# และ Php

one text

ฉันต้องการส่งข้อมูลที่เข้ารหัสจากแอปพลิเคชันใน C# ไปยังบริการเว็บภายนอกที่เขียนด้วย PHP (เป็นเว็บแอปพลิเคชันบุคคลที่สามที่ฉันไม่สามารถควบคุมได้) ฉันได้รับข้อมูลโค้ดต่อไปนี้เกี่ยวกับตรรกะการเข้ารหัสที่ใช้ในแอปพลิเคชัน PHP:

\n
 $data = \'data to be sent\';\n    $base64data = base64_encode($data);     \n    $ciphering = "AES-128-CBC"; \n    $iv_length = openssl_cipher_iv_length($ciphering); \n    $options = 0; \n    $encryption_iv = \'1234567891234567\'; \n    $encryption_key = md5(\'123456789\'); \n    $encryptedData= base64_encode(openssl_encrypt($base64data, $ciphering, \n                                                  $encryption_key, $options, $encryption_iv));\n
\ n

ฉันได้เขียนการใช้งานต่อไปนี้ใน C# แต่ผลลัพธ์ของการเข้ารหัสแตกต่างจากที่สร้างจากโค้ด PHP

\n
 string data = "data to be sent";\n            string base64data = Convert.ToBase64String(Encoding.UTF8.GetBytes(data));\n\n            // Encryption key is MD5 hash of value: \'123456789\'\n            MD5 hasher = MD5.Create();\n            byte[] HashValue = hasher.ComputeHash(Encoding.UTF8.GetBytes("123456789"));\n            string encryptionKey = "";\n            foreach (byte b in HashValue)\n            {\n                encryptionKey += b.ToString("x2");\n            }\n            byte[] keyBytes = Encoding.UTF8.GetBytes(encryptionKey);\n\n            byte[] iv = Encoding.UTF8.GetBytes("1234567891234567");\n\n            RijndaelManaged aes = new RijndaelManaged();\n            aes.Mode = CipherMode.CBC;\n            aes.KeySize = 128;\n            aes.Key = keyBytes;\n            aes.IV = iv;\n            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);\n            MemoryStream msEncrypt = new MemoryStream();\n            CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);\n            StreamWriter swEncrypt = new StreamWriter(csEncrypt);\n\n            swEncrypt.Write(base64data);\n\n            swEncrypt.Close();\n            csEncrypt.Close();\n            aes.Clear();\n            aes.Clear();\n            byte[] encryptedData = msEncrypt.ToArray();\n\n            Console.WriteLine($"Encrypted data: {Convert.ToBase64String(encryptedData)}"); \n 
\n

โปรดทราบว่าฉันยังใช้คลาส AesManaged ใน .NET และคลาสที่เกี่ยวข้องในไลบรารี BouncyCastle.Crypto เพื่อทำการเข้ารหัสใน C# (ในกรณีที่ฉันอาจพลาดบางสิ่งไป ในการดำเนินการของฉัน) ในทุกกรณี ผลลัพธ์ที่สร้างขึ้นใน C# (แน่นอนว่าเหมือนกันไม่ว่าจะใช้ไลบรารีใดใน .NET) จะแตกต่างจากผลลัพธ์ที่สร้างจากโค้ด PHP ใครสามารถให้ข้อมูลเกี่ยวกับสิ่งที่อาจเป็นปัญหาได้บ้าง

\n

Source