Completed
Push — master ( dd0bc2...b5fd08 )
by Oscar
03:27
created

CryptTrait::crypt()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
rs 8.8571
cc 5
eloc 7
nc 2
nop 2
1
<?php
2
3
namespace Psr7Middlewares\Utils;
4
5
use RuntimeException;
6
use phpseclib\Crypt\AES;
7
8
/**
9
 * Trait used by all middlewares that needs encrypt/decrypt functions
10
 */
11
trait CryptTrait
12
{
13
    protected $cipher;
14
15
    /**
16
     * Set the key
17
     * 
18
     * @param string $key
19
     *
20
     * @return self
21
     */
22
    public function key($key)
23
    {
24
        $this->cipher = new AES();
25
        $this->cipher->setKey($key);
26
27
        return $this;
28
    }
29
30
    /**
31
     * Encrypt the given value.
32
     *
33
     * @param string $value
34
     * 
35
     * @return string
36
     */
37
    protected function encrypt($value)
38
    {
39
        if ($this->cipher) {
40
            return bin2hex($this->cipher->encrypt($value));
41
        }
42
43
        return $value;
44
    }
45
46
    /**
47
     * Decrypt the given value.
48
     *
49
     * @param string $value
50
     * 
51
     * @return string
52
     */
53
    protected function decrypt($value)
54
    {
55
        if ($this->cipher) {
56
            return $this->cipher->decrypt(hex2bin($value));
57
        }
58
59
        return $value;
60
    }
61
}
62