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 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号