问题
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:
- Get the right source code, e.g. for 4.2.16;
- Get it to work on your machine. Make sure you run on the same PHP environment (using OpenSSL extensions for the latest versions);
- Instantiate the class in
Encrypter
with the correct key, and possibly set the correct mode and algorithm; - 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