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

OpenSSL   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 0
dl 0
loc 50
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A openssl_encrypt() 0 6 1
A openssl_decrypt() 0 6 1
A returnOrException() 0 8 2
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