Completed
Pull Request — master (#1035)
by Matt
03:17
created

CryptTrait   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 78.95%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 1
dl 0
loc 69
rs 10
c 0
b 0
f 0
ccs 15
cts 19
cp 0.7895

3 Methods

Rating   Name   Duplication   Size   Complexity  
A encrypt() 0 16 4
A decrypt() 0 16 4
A setEncryptionKey() 0 4 1
1
<?php
2
/**
3
 * Encrypt/decrypt with encryptionKey.
4
 *
5
 * @author      Alex Bilbie <[email protected]>
6
 * @copyright   Copyright (c) Alex Bilbie
7
 * @license     http://mit-license.org/
8
 *
9
 * @link        https://github.com/thephpleague/oauth2-server
10
 */
11
12
namespace League\OAuth2\Server;
13
14
use Defuse\Crypto\Crypto;
15
use Defuse\Crypto\Key;
16
use Exception;
17
use LogicException;
18
19
trait CryptTrait
20
{
21
    /**
22
     * @var string|Key|null
23
     */
24
    protected $encryptionKey;
25
26
    /**
27
     * Encrypt data with encryptionKey.
28
     *
29
     * @param string $unencryptedData
30
     *
31
     * @throws LogicException
32
     *
33
     * @return string
34
     */
35 36
    protected function encrypt($unencryptedData)
36
    {
37
        try {
38 36
            if ($this->encryptionKey instanceof Key) {
39 1
                return Crypto::encrypt($unencryptedData, $this->encryptionKey);
40
            }
41
42 35
            if (is_string($this->encryptionKey)) {
43 35
                return Crypto::encryptWithPassword($unencryptedData, $this->encryptionKey);
44
            }
45
46
            throw new LogicException('Encryption key not set when attempting to encrypt');
47
        } catch (Exception $e) {
48
            throw new LogicException($e->getMessage(), 0, $e);
49
        }
50
    }
51
52
    /**
53
     * Decrypt data with encryptionKey.
54
     *
55
     * @param string $encryptedData
56
     *
57
     * @throws LogicException
58
     *
59
     * @return string
60
     */
61 30
    protected function decrypt($encryptedData)
62
    {
63
        try {
64 30
            if ($this->encryptionKey instanceof Key) {
65 1
                return Crypto::decrypt($encryptedData, $this->encryptionKey);
66
            }
67
68 29
            if (is_string($this->encryptionKey)) {
69 29
                return Crypto::decryptWithPassword($encryptedData, $this->encryptionKey);
70
            }
71
72
            throw new LogicException('Encryption key not set when attempting to decrypt');
73 2
        } catch (Exception $e) {
74 2
            throw new LogicException($e->getMessage(), 0, $e);
75
        }
76
    }
77
78
    /**
79
     * Set the encryption key
80
     *
81
     * @param string|Key $key
82
     */
83 88
    public function setEncryptionKey($key = null)
84
    {
85 88
        $this->encryptionKey = $key;
86 88
    }
87
}
88