Client::encryptAES()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 10
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
namespace DeveloperH\Knet\SDK;
4
5
class Client
6
{
7
    public function decrypt($code, $key)
8
    {
9
        $code = $this->hex2ByteArray(trim($code));
10
        $code = $this->byteArray2String($code);
11
        $iv = $key;
12
        $code = base64_encode($code);
13
        $decrypted = openssl_decrypt($code, 'AES-128-CBC', $key, OPENSSL_ZERO_PADDING, $iv);
14
15
        return $this->pkcs5_unpad($decrypted);
16
    }
17
18
    public function hex2ByteArray($hexString)
19
    {
20
        $string = hex2bin($hexString);
21
22
        return unpack('C*', $string);
23
    }
24
25
    public function byteArray2String($byteArray)
26
    {
27
        $chars = array_map('chr', $byteArray);
28
29
        return implode($chars);
30
    }
31
32
    public function pkcs5_unpad($text)
33
    {
34
        $pad = ord($text[strlen($text) - 1]);
35
        if ($pad > strlen($text)) {
36
            return '';
37
        }
38
        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
39
            return '';
40
        }
41
42
        return substr($text, 0, -1 * $pad);
43
    }
44
45
    public function encryptAES($str, $key)
46
    {
47
        $str = $this->pkcs5_pad($str);
48
        $encrypted = openssl_encrypt($str, 'AES-128-CBC', $key, OPENSSL_ZERO_PADDING, $key);
49
        $encrypted = base64_decode($encrypted);
50
        $encrypted = unpack('C*', ($encrypted));
51
        $encrypted = $this->byteArray2Hex($encrypted);
52
        $encrypted = urlencode($encrypted);
53
54
        return $encrypted;
55
    }
56
57
    public function pkcs5_pad($text)
58
    {
59
        $blocksize = 16;
60
        $pad = $blocksize - (strlen($text) % $blocksize);
61
62
        return $text.str_repeat(chr($pad), $pad);
63
    }
64
65
    public function byteArray2Hex($byteArray)
66
    {
67
        $chars = array_map('chr', $byteArray);
68
        $bin = implode($chars);
69
70
        return bin2hex($bin);
71
    }
72
}
73