douqu2481 2014-01-28 19:01
浏览 106
已采纳

将Laravel的AES 256加密器转换为C#

I need to create the same results when using Crypt::Encrypt('secret') from Laravel, in C#. I found this thread Rijndael 256 Encrypt/decrypt between c# and php? and it seemed to be what I need, but I'm having some trouble with the third argument the, initialization vector :(.

Laravel using Rijndael AES to encrypt the data. All the user has to input is a secret key, in the config folder, that is totally random and 32 characters long.

The encyrption method looks like this:

public function encrypt($value)
    {
        $iv = mcrypt_create_iv($this->getIvSize(), $this->getRandomizer());

        $value = base64_encode($this->padAndMcrypt($value, $iv));

        // Once we have the encrypted value we will go ahead base64_encode the input
        // vector and create the MAC for the encrypted value so we can verify its
        // authenticity. Then, we'll JSON encode the data in a "payload" array.
        $mac = $this->hash($iv = base64_encode($iv), $value);

        return base64_encode(json_encode(compact('iv', 'value', 'mac')));
    }

The full Encryptor.php can be found here: http://pastebin.com/yfWLPxGn

Any idea as to what I would have to input to get the same results? :)

  • 写回答

2条回答 默认 最新

  • dongzhao3040 2014-02-18 13:16
    关注

    Initialization vector is an input that is typically random. So, algorithm always creates a different value using the same input, key and the different IV. If you'd like to generate same result using both PHP and C# code, you need to use the same IV value.

    Laravel's encrypt() does not return the encrypted value only. The value encrypt() generates a base64 encoded string which has json encoded values of iv, mac and encrypted value.

    So the steps you need to apply in your C# encode() method:

    1. Encode the string using the code in the link you gave.
    2. base64_encode() the encrypted value. We will use this value in the further steps.
    3. Create MAC (Message Authentication Code) using base64_encoded IV as the value, encrypted value as the key and sha256 as the algorithm. Take a look at this one
    4. Now we have encrypted value, mac and iv.
    5. Create a json string like this:

      { 
          iv: iv value (base64 encoded),
          value: encrypted value (base64 encoded), 
          mac: mac value created in 3rd step 
      }
      
    6. base64 encode your this json string.

    7. You're all set.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失