Completed
Push — master ( 49d749...625fb3 )
by Michael
02:45 queued 01:14
created

OpenSSL::returnOpensslOutput()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
3
/**
4
 * OpenSSL.php
5
 *
6
 * PHP version 7
7
 *
8
 * @category Dcrypt
9
 * @package  Dcrypt
10
 * @author   Michael Meyer (mmeyer2k) <[email protected]>
11
 * @license  http://opensource.org/licenses/MIT The MIT License (MIT)
12
 * @link     https://github.com/mmeyer2k/dcrypt
13
 */
14
15
namespace Dcrypt;
16
17
class OpenSSL
18
{
19
    /**
20
     * OpenSSL encrypt wrapper function
21
     *
22
     * @param string $data   Data to decrypt
23
     * @param string $method Cipher method to use
24
     * @param string $key    Key string
25
     * @param string $iv     Initialization vector
26
     * @return string
27
     */
28
    protected static function openssl_encrypt(string $data, string $method, string $key, string $iv): string
29
    {
30
        $ret = \openssl_encrypt($data, $method, $key, 1, $iv);
31
32
        return self::returnOrException($ret);
33
    }
34
35
    /**
36
     * OpenSSL decrypt wrapper function
37
     *
38
     * @param string $data   Data to decrypt
39
     * @param string $method Cipher method to use
40
     * @param string $key    Key string
41
     * @param string $iv     Initialization vector
42
     * @return string
43
     */
44
    protected static function openssl_decrypt(string $data, string $method, string $key, string $iv): string
45
    {
46
        $ret = \openssl_decrypt($data, $method, $key, 1, $iv);
47
48
        return self::returnOrException($ret);
49
    }
50
51
    /**
52
     * Throw an exception if openssl function returns false
53
     *
54
     * @param string|bool $data
55
     * @return string
56
     * @throws \Exception
57
     */
58
    private static function returnOrException($data): string
59
    {
60
        if ($data === false) {
61
            throw new \Exception('OpenSSL failed to encrypt/decrypt message.');
62
        }
63
64
        return $data;
65
    }
66
}
67