1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* OpensslWrapper.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 OpensslWrapper |
18
|
|
|
{ |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* OpenSSL encrypt wrapper function |
22
|
|
|
* |
23
|
|
|
* @param string $data Data to decrypt |
24
|
|
|
* @param string $method Cipher method to use |
25
|
|
|
* @param string $key Key string |
26
|
|
|
* @param string $iv Initialization vector |
27
|
|
|
* @return string |
28
|
|
|
*/ |
29
|
|
|
public static function encrypt(string $data, string $method, string $key, string $iv): string |
30
|
|
|
{ |
31
|
|
|
$ret = \openssl_encrypt($data, $method, $key, 1, $iv); |
32
|
|
|
|
33
|
|
|
return self::returnOrException($ret); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* OpenSSL decrypt wrapper function |
38
|
|
|
* |
39
|
|
|
* @param string $data Data to decrypt |
40
|
|
|
* @param string $method Cipher method to use |
41
|
|
|
* @param string $key Key string |
42
|
|
|
* @param string $iv Initialization vector |
43
|
|
|
* @return string |
44
|
|
|
*/ |
45
|
|
|
public static function decrypt(string $data, string $method, string $key, string $iv): string |
46
|
|
|
{ |
47
|
|
|
$ret = \openssl_decrypt($data, $method, $key, 1, $iv); |
48
|
|
|
|
49
|
|
|
return self::returnOrException($ret); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Throw an exception if openssl function returns false |
54
|
|
|
* |
55
|
|
|
* @param string|bool $data |
56
|
|
|
* @return string |
57
|
|
|
* @throws \Exception |
58
|
|
|
*/ |
59
|
|
|
private static function returnOrException($data): string |
60
|
|
|
{ |
61
|
|
|
if ($data === false) { |
62
|
|
|
throw new \Exception('OpenSSL failed to encrypt/decrypt message.'); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return $data; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|