oauth2-server/src/CryptTrait.php

88 lines
2.1 KiB
PHP
Raw Normal View History

2016-01-14 23:44:39 +00:00
<?php
/**
* Encrypt/decrypt with encryptionKey.
2017-10-23 15:26:10 +00:00
*
2016-01-14 23:44:39 +00:00
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
2017-10-23 15:26:10 +00:00
*
2016-01-14 23:44:39 +00:00
* @link https://github.com/thephpleague/oauth2-server
*/
2016-07-09 01:00:44 +02:00
2016-03-17 14:37:21 +00:00
namespace League\OAuth2\Server;
2016-01-14 23:44:39 +00:00
use Defuse\Crypto\Crypto;
use Defuse\Crypto\Key;
2018-11-13 01:00:23 +01:00
use Exception;
use LogicException;
2016-03-17 14:37:21 +00:00
trait CryptTrait
2016-01-14 23:44:39 +00:00
{
/**
2019-07-01 19:17:43 +01:00
* @var string|Key|null
*/
protected $encryptionKey;
2016-01-14 23:44:39 +00:00
/**
2018-06-04 16:32:02 +03:00
* Encrypt data with encryptionKey.
2016-01-14 23:44:39 +00:00
*
* @param string $unencryptedData
*
2018-11-13 01:00:23 +01:00
* @throws LogicException
2017-10-23 15:26:10 +00:00
*
2016-01-14 23:44:39 +00:00
* @return string
*/
2016-03-17 14:37:21 +00:00
protected function encrypt($unencryptedData)
2016-01-14 23:44:39 +00:00
{
try {
if ($this->encryptionKey instanceof Key) {
return Crypto::encrypt($unencryptedData, $this->encryptionKey);
}
2018-02-28 20:33:19 +00:00
2019-07-01 19:17:43 +01:00
if (is_string($this->encryptionKey)) {
return Crypto::encryptWithPassword($unencryptedData, $this->encryptionKey);
}
throw new LogicException('Encryption key not set when attempting to encrypt');
2018-11-13 01:00:23 +01:00
} catch (Exception $e) {
2019-07-01 19:17:43 +01:00
throw new LogicException($e->getMessage(), 0, $e);
}
2016-01-14 23:44:39 +00:00
}
/**
2018-06-04 16:32:02 +03:00
* Decrypt data with encryptionKey.
2016-01-14 23:44:39 +00:00
*
* @param string $encryptedData
*
2018-11-13 01:00:23 +01:00
* @throws LogicException
2017-10-23 15:26:10 +00:00
*
2016-01-14 23:44:39 +00:00
* @return string
*/
2016-03-17 14:37:21 +00:00
protected function decrypt($encryptedData)
2016-01-14 23:44:39 +00:00
{
try {
if ($this->encryptionKey instanceof Key) {
return Crypto::decrypt($encryptedData, $this->encryptionKey);
}
2018-02-28 20:33:19 +00:00
2019-07-01 19:17:43 +01:00
if (is_string($this->encryptionKey)) {
return Crypto::decryptWithPassword($encryptedData, $this->encryptionKey);
}
throw new LogicException('Encryption key not set when attempting to decrypt');
2018-11-13 01:00:23 +01:00
} catch (Exception $e) {
2019-07-01 19:17:43 +01:00
throw new LogicException($e->getMessage(), 0, $e);
}
2016-01-14 23:44:39 +00:00
}
/**
* Set the encryption key
*
* @param string|Key $key
*/
public function setEncryptionKey($key = null)
{
$this->encryptionKey = $key;
}
2016-03-17 10:37:48 -04:00
}