Completed
Push — master ( 05a429...b45f19 )
by Gabriel
10:23 queued 05:22
created

Helper::recursiveKeySort()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
cc 3
eloc 4
nc 3
nop 1
crap 3
1
<?php
2
3
namespace ByTIC\Omnipay\Twispay;
4
5
/**
6
 * Class Helper
7
 * @package ByTIC\Omnipay\Twispay
8
 */
9
class Helper
10
{
11
    /**
12
     * @param array $data
13
     * @param string $key
14
     * @return string
15
     */
16 1
    public static function generateChecksum(array $data, string $key)
17
    {
18 1
        unset($data['checksum']);
19 1
        self::recursiveKeySort($data);
20 1
        $query = http_build_query($data);
21 1
        $encoded = hash_hmac('sha512', $query, $key, true);
22 1
        return base64_encode($encoded);
23
    }
24
25
    /**
26
     * @param array $data
27
     */
28 1
    private static function recursiveKeySort(array &$data)
29
    {
30 1
        ksort($data, SORT_STRING);
31 1
        foreach ($data as $key => $value) {
32 1
            if (is_array($value)) {
33 1
                self::recursiveKeySort($data[$key]);
34
            }
35
        }
36 1
    }
37
38
    /**
39
     * @param string $encrypted
40
     * @param $key
41
     * @return null|string
42
     * @throws \Exception
43
     */
44
    public static function decrypt(string $encrypted, $key)
45
    {
46
        if (strpos($encrypted, ',') !== false) {
47
            $encryptedParts = explode(',', $encrypted, 2);
48
            $iv = base64_decode($encryptedParts[0]);
49
            if ($iv === false) {
50
                throw new \Exception('Invalid encryption iv');
51
            }
52
            $encrypted = base64_decode($encryptedParts[1]);
53
            if ($encrypted === false) {
54
                throw new \Exception('Invalid encrypted data');
55
            }
56
            $decrypted = openssl_decrypt($encrypted, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
0 ignored issues
show
Bug introduced by
ByTIC\Omnipay\Twispay\OPENSSL_RAW_DATA of type integer is incompatible with the type boolean expected by parameter $raw_input of openssl_decrypt(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

56
            $decrypted = openssl_decrypt($encrypted, 'aes-256-cbc', $key, /** @scrutinizer ignore-type */ OPENSSL_RAW_DATA, $iv);
Loading history...
57
            if ($decrypted === false) {
58
                throw new \Exception('Cannot decrypt data');
59
            }
60
            return $decrypted;
61
        }
62
        return null;
63
    }
64
}