Passed
Push — main ( 006c6c...060baa )
by Miaad
02:32
created

encrypt::shortDecode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 8
rs 10
1
<?php
2
3
namespace BPT\tools;
4
5
use BPT\constants\cryptoAction;
6
use BPT\constants\loggerTypes;
7
use BPT\exception\bptException;
8
use BPT\logger;
9
10
trait encrypt {
11
    /**
12
     * encrypt or decrypt a text with really high security
13
     *
14
     * action parameter must be encrypt or decrypt
15
     *
16
     * string parameter is your hash(received when use encrypt) or the text you want to encrypt
17
     *
18
     * for decrypt , you must have key and iv parameter. you can found them in result of encrypt
19
     *
20
     * e.g. => tools::crypto(action: 'decrypt', text: '9LqUf9DSuRRwfo03RnA5Kw==', key: '39aaadf402f9b921b1d44e33ee3b022716a518e97d6a7b55de8231de501b4f34', iv: 'a2e5904a4110169e');
21
     *
22
     * e.g. => tools::crypto(cryptoAction::ENCRYPT,'hello world');
23
     *
24
     * @param string      $action e.g. => cryptoAction::ENCRYPT | 'encrypt'
25
     * @param string      $text   e.g. => 'hello world'
26
     * @param null|string $key    e.g. => Optional, 39aaadf402f9b921b1d44e33ee3b022716a518e97d6a7b55de8231de501b4f34
27
     * @param null|string $iv     e.g. => Optional, a2e5904a4110169e
28
     *
29
     * @return string|bool|array{hash:string, key:string, iv:string}
30
     * @throws bptException
31
     */
32
    public static function crypto (string $action, string $text, string $key = null, string $iv = null): bool|array|string {
33
        if (extension_loaded('openssl')) {
34
            if ($action === cryptoAction::ENCRYPT) {
35
                $key = self::randomString(64);
36
                $iv = self::randomString();
37
                $output = base64_encode(openssl_encrypt($text, 'AES-256-CBC', $key, 1, $iv));
38
                return ['hash' => $output, 'key' => $key, 'iv' => $iv];
39
            }
40
            elseif ($action === cryptoAction::DECRYPT) {
41
                if (empty($key)) {
42
                    logger::write("tools::crypto function used\nkey parameter is not set",loggerTypes::ERROR);
43
                    throw new bptException('ARGUMENT_NOT_FOUND_KEY');
44
                }
45
                elseif (empty($iv)) {
46
                    logger::write("tools::crypto function used\niv parameter is not set",loggerTypes::ERROR);
47
                    throw new bptException('ARGUMENT_NOT_FOUND_IV');
48
                }
49
                return openssl_decrypt(base64_decode($text), 'AES-256-CBC', $key, 1, $iv);
50
            }
51
            else {
52
                logger::write("tools::crypto function used\naction is not right, its must be `encode` or `decode`",loggerTypes::WARNING);
53
                return false;
54
            }
55
        }
56
        else {
57
            logger::write("tools::crypto function used\nopenssl extension is not found , It may not be installed or enabled",loggerTypes::ERROR);
58
            throw new bptException('OPENSSL_EXTENSION_MISSING');
59
        }
60
    }
61
62
    /**
63
     * encode int to a string
64
     *
65
     * e.g. => tools::shortEncode(123456789);
66
     *
67
     * @param int $num
68
     *
69
     * @return string
70
     */
71
    public static function shortEncode(int $num): string {
72
        $codes = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
73
        $array = [];
74
        while ($num > 0){
75
            $array[] = $num % 62;
76
            $num = floor($num / 62);
77
        }
78
        if (count($array) < 1) $array = [0];
79
        foreach ($array as &$value) {
80
            $value = $codes[$value];
81
        }
82
        return strrev(implode('',$array));
83
    }
84
85
    /**
86
     * decode string to int
87
     *
88
     * e.g. => tools::shortDecode('8m0Kx');
89
     *
90
     * @param string $text
91
     *
92
     * @return int
93
     */
94
    public static function shortDecode(string $text): int{
95
        $codes = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
96
        $num = 0;
97
        $text = str_split(strrev($text));
98
        foreach ($text as $key=>$value) {
99
            $num += strpos($codes,$value) * pow(62,$key);
100
        }
101
        return $num;
102
    }
103
}