从C#向PHP发送加密消息


send encrypted message from C# to PHP

我试图让两个服务进行对话,但我需要加密它们之间发送的消息。现在还为时过早,所以我正在努力编写密钥,但这是我迄今为止所拥有的。

在c#中

byte[] key = Convert.FromBase64String("QM3M8+Zbw5VYa70xtftksHHqM1UGmhOBjqOP82UtuAA=");
byte[] hexiv = Convert.FromBase64String("wRt00heBiu86mWSfuHmSag==");
using (RijndaelManaged myRijndael = new RijndaelManaged())
  {
    byte[] encrypted = EncryptStringToBytes(name, myRijndael.Key, myRijndael.IV);
    string enc = Convert.ToBase64String(encrypted);
  }
.....

static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
    {
        // Check arguments. 
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("Key");
        byte[] encrypted;
        // Create an RijndaelManaged object 
        // with the specified key and IV. 
        using (RijndaelManaged rijAlg = new RijndaelManaged())
        {
            rijAlg.Key = Key;
            rijAlg.IV = IV;
            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
            // Create the streams used for encryption. 
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }

这将我的消息输出为+CPJqIL6RhIHc5+u2Nvonw==

然后在PHP中,我有以下内容:

$key = "Zbw5VYa70xtftksHHqM1UGmhOBjqOP82UtuAA=";
$hexiv = "wRt00heBiu86mWSfuHmSag==";
$string = base64_decode("+CPJqIL6RhIHc5+u2Nvonw==");
$cipher_alg = MCRYPT_RIJNDAEL_256;
$decrypted_string = mcrypt_decrypt($cipher_alg, $key, $string , MCRYPT_MODE_CBC, $hexiv);
echo $decrypted_string."<BR>";

但这给了我Qˆ–⤻?/P¸Üu:·ey+–Uñ :,yL±­M

希望答案很明显,但我看不出来。

您落入了mcrypt陷阱。

MCRYPT_RIJNDAEL_256不是AES-256,它是Rijndael的256位块大小变体。即使使用256位密钥,AES也始终是128位块大小。

转而研究利钠。有.NET和PHP的绑定。如果你升级到PHP 7.2或更高版本,你应该已经安装好了。