将加密的消息从C#发送到PHP

时间:2013-12-04 16:22:40

标签: c# php encryption

我正在尝试使用两种服务进行通话,但我需要加密它们之间发送的消息。这是早期的,所以我很难对密钥进行编码,但这是我到目前为止所做的。

在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

希望答案相当明显,但我看不到它。

1 个答案:

答案 0 :(得分:0)

您爱上了the mcrypt trap

Fri, 12:31 am Thu, 10:00 am Thu, 02:30 pm 不是AES-256,它是Rijndael的256位块大小变体。即使使用256位密钥,AES始终是128位块大小。

改为查看libsodium。有.NET和PHP的绑定。如果您升级到PHP 7.2或更高版本,则应该已经安装了它。