forked from thephpleague/oauth2-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCryptTrait.php
More file actions
90 lines (75 loc) · 2.64 KB
/
Copy pathCryptTrait.php
File metadata and controls
90 lines (75 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
/**
* Encrypt/decrypt with encryptionKey.
*
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
*
* @link https://github.com/thephpleague/oauth2-server
*/
declare(strict_types=1);
namespace League\OAuth2\Server;
use Defuse\Crypto\Crypto;
use Defuse\Crypto\Exception\EnvironmentIsBrokenException;
use Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException;
use Defuse\Crypto\Key;
use Exception;
use InvalidArgumentException;
use LogicException;
use function is_string;
trait CryptTrait
{
protected string|Key|null $encryptionKey = null;
/**
* Encrypt data with encryptionKey.
*
* @throws LogicException
*/
protected function encrypt(string $unencryptedData): string
{
try {
if ($this->encryptionKey instanceof Key) {
return Crypto::encrypt($unencryptedData, $this->encryptionKey);
}
if (is_string($this->encryptionKey)) {
return Crypto::encryptWithPassword($unencryptedData, $this->encryptionKey);
}
throw new LogicException('Encryption key not set when attempting to encrypt');
} catch (Exception $e) {
throw new LogicException($e->getMessage(), 0, $e);
}
}
/**
* Decrypt data with encryptionKey.
*
* @throws LogicException
*/
protected function decrypt(string $encryptedData): string
{
try {
if ($this->encryptionKey instanceof Key) {
return Crypto::decrypt($encryptedData, $this->encryptionKey);
}
if (is_string($this->encryptionKey)) {
return Crypto::decryptWithPassword($encryptedData, $this->encryptionKey);
}
throw new LogicException('Encryption key not set when attempting to decrypt');
} catch (WrongKeyOrModifiedCiphertextException $e) {
$exceptionMessage = 'The authcode or decryption key/password used '
. 'is not correct';
throw new InvalidArgumentException($exceptionMessage, 0, $e);
} catch (EnvironmentIsBrokenException $e) {
$exceptionMessage = 'Auth code decryption failed. This is likely '
. 'due to an environment issue or runtime bug in the '
. 'decryption library';
throw new LogicException($exceptionMessage, 0, $e);
} catch (Exception $e) {
throw new LogicException($e->getMessage(), 0, $e);
}
}
public function setEncryptionKey(Key|string|null $key = null): void
{
$this->encryptionKey = $key;
}
}