Completed
Pull Request — master (#1102)
by
unknown
08:28
created

CryptTrait   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Test Coverage

Coverage 66.67%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 19
c 2
b 0
f 0
dl 0
loc 67
ccs 12
cts 18
cp 0.6667
rs 10
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setEncryptionKey() 0 3 1
A decrypt() 0 14 4
A encrypt() 0 14 4
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 23
    protected function encrypt($unencryptedData)
36
    {
37
        try {
38 23
            if ($this->encryptionKey instanceof Key) {
39
                return Crypto::encrypt($unencryptedData, $this->encryptionKey);
40
            }
41
42 23
            if (\is_string($this->encryptionKey)) {
43 23
                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 21
    protected function decrypt($encryptedData)
62
    {
63
        try {
64 21
            if ($this->encryptionKey instanceof Key) {
65
                return Crypto::decrypt($encryptedData, $this->encryptionKey);
66
            }
67
68 21
            if (\is_string($this->encryptionKey)) {
69 21
                return Crypto::decryptWithPassword($encryptedData, $this->encryptionKey);
70
            }
71
72
            throw new LogicException('Encryption key not set when attempting to decrypt');
73 1
        } catch (Exception $e) {
74 1
            throw new LogicException($e->getMessage(), 0, $e);
75
        }
76
    }
77
78
    /**
79
     * Set the encryption key
80
     *
81
     * @param string|Key $key
82
     */
83 69
    public function setEncryptionKey($key = null)
84
    {
85 69
        $this->encryptionKey = $key;
86 69
    }
87
}
88