Completed
Push — master ( 5c7564...a0a1f5 )
by Lawrence
01:31
created

Signer::encode()   B

Complexity

Conditions 6
Paths 2

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 11
nc 2
nop 1
dl 0
loc 19
ccs 0
cts 0
cp 0
crap 42
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/*
3
 +------------------------------------------------------------------------+
4
 | Plinker-RPC PHP                                                        |
5
 +------------------------------------------------------------------------+
6
 | Copyright (c)2017-2018 (https://github.com/plinker-rpc/core)           |
7
 +------------------------------------------------------------------------+
8
 | This source file is subject to MIT License                             |
9
 | that is bundled with this package in the file LICENSE.                 |
10
 |                                                                        |
11
 | If you did not receive a copy of the license and are unable to         |
12
 | obtain it through the world-wide-web, please send an email             |
13
 | to [email protected] so we can send you a copy immediately.        |
14
 +------------------------------------------------------------------------+
15
 | Authors: Lawrence Cherone <[email protected]>                     |
16
 +------------------------------------------------------------------------+
17
 */
18
19
namespace Plinker\Core\Lib;
20
21
use Opis\Closure\SerializableClosure;
22
23
/**
24
 * Plinker\Core\Lib\Signer
25
 */
26
final class Signer
27
{
28
    /**
29
     * @var
30
     */
31
    private $config;
32
33
    /**
34
     * Class construct
35
     *
36
     * @param  array  $config  - config array which holds object configuration
37
     * @return void
38
     */
39 2
    public function __construct($config = [])
40
    {
41
        //
42 2
        $this->config = array_merge([
43 2
            "secret" => null
44 2
        ], $config);
45
46
        // hash secret
47 2
        if (isset($this->config["secret"])) {
48 2
            $this->config["secret"] = hash("sha256", gmdate("h").$this->config["secret"]);
49
        }
50 2
    }
51
52
    /**
53
     * @codeCoverageIgnore
54
     */
55
    private function encrypt($plaintext, $password)
56
    {
57
        $method     = "AES-256-CBC";
58
        $key        = (string) hash("sha256", $password, true);
59
        $iv         = (string) openssl_random_pseudo_bytes(16);
60
        $ciphertext = (string) openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv);
61
62
        $hash = (string) hash_hmac("sha256", $ciphertext, $key, true);
63
64
        return base64_encode($iv . $hash . $ciphertext);
65
    }
66
67
    /**
68
     * @codeCoverageIgnore
69
     */
70
    private function decrypt($ciphertext, $password)
71
    {
72
        $ciphertext    = base64_decode($ciphertext);
73
74
        $method     = "AES-256-CBC";
75
        $iv         = substr($ciphertext, 0, 16);
76
        $hash       = substr($ciphertext, 16, 32);
77
        $ciphertext = substr($ciphertext, 48);
78
        $key        = (string) hash("sha256", $password, true);
79
80
        if (hash_hmac("sha256", $ciphertext, $key, true) !== $hash) {
81
            return null;
82
        }
83
84
        return openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv);
85
    }
86
87
    /**
88
     * Sign and encrypt into payload array.
89
     *
90
     * @codeCoverageIgnore
91
     *
92
     * @return array
93
     */
94
    public function encode($data)
95
    {
96
        // loop over params, look for closure
97
        if (isset($data['params']) && is_array($data['params'])) {
98
            foreach ($data['params'] as $key => $param) {
99
                if (is_object($param) && ($param instanceof \Closure)) {
100
                    $data['params'][$key] = new SerializableClosure($param);
101
                }
102
            }
103
        }
104
        
105
        $data = serialize($data);
106
107
        return [
108
            "data"  => $this->encrypt($data, $this->config["secret"]),
109
            "token" => hash_hmac(
110
                "sha256",
111
                $data,
112
                $this->config["secret"]
113
            )
114
        ];
115
    }
116
117
    /**
118
     * Decrypt, verify and unserialize payload.
119
     *
120
     * @codeCoverageIgnore
121
     *
122
     * @return mixed
123
     */
124
    public function decode($data)
125
    {
126
        $data["data"] = $this->decrypt($data["data"], $this->config["secret"]);
127
128
        if (hash_hmac(
129
            "sha256",
130
            $data["data"],
131
            $this->config["secret"]
132
        ) == $data["token"]) {
133
            return unserialize($data["data"]);
134
        } else {
135
            throw new \Exception('Failed to verify payload');
136
        }
137
    }
138
}
139