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 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退