Decrypt encrypted value outside of Laravel

拥有回忆 提交于 2019-12-10 15:59:42

问题


How can i decrypt a string which has been encrypted using the Laravel 4 Encrypt class, outside of Laravel, only with PHP?


回答1:


The Laravel Encrypter class uses Rijndael with a block size of 256 bit for encryption which is provided by the Mcrypt PHP extension. The Encrypter class works using two simple methods, encrypt() and decrypt().

An example below:

<?php

$secret = Crypter::encrypt('some text here'); //encrypted

$decrypted_secret = Crypter::decrypt($secret); //decrypted

?>

Since you're asking how to do it "outside of Laravel":

The encryption and decryption is done by the encrypter class. Laravel source is public and here's the relevant part:

<?php

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

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

    protected function padAndMcrypt($value, $iv)
    {
        $value = $this->addPadding(serialize($value));
        return mcrypt_encrypt($this->cipher, $this->key, $value, $this->mode, $iv);
    }

    public function decrypt($payload)
    {
        $payload = $this->getJsonPayload($payload);
        $value = base64_decode($payload['value']);
        $iv = base64_decode($payload['iv']);
        return unserialize($this->stripPadding($this->mcryptDecrypt($value, $iv)));
    }

    protected function mcryptDecrypt($value, $iv)
    {
        return mcrypt_decrypt($this->cipher, $this->key, $value, $this->mode, $iv);
    }

?>

For documentation and comments, see Laravel source code on GitHub.

I hope this helps.




回答2:


The Encrypter class of Laravel is prone to changes. This is due to some security vulnerabilities that got fixed. So to successfully decrypt you need to do the following things:

  1. Get the right source code, e.g. for 4.2.16;
  2. Get it to work on your machine. Make sure you run on the same PHP environment (using OpenSSL extensions for the latest versions);
  3. Instantiate the class in Encrypter with the correct key, and possibly set the correct mode and algorithm;
  4. Finally, call decrypt.

All other required parameters for decryption (IV and MAC value) should be contained within the ciphertext.



来源:https://stackoverflow.com/questions/17390898/decrypt-encrypted-value-outside-of-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!