-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_encryptor.php
97 lines (88 loc) · 2.53 KB
/
simple_encryptor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
namespace PMVC\PlugIn\simple_encryptor;
use UnexpectedValueException;
${_INIT_CONFIG}[_CLASS] = __NAMESPACE__ . '\SimpleEncryptor';
class SimpleEncryptor extends \PMVC\PlugIn
{
private $_methods;
public function init()
{
if (!isset($this['method'])) {
$this['method'] = 'aes-256-cfb';
}
}
private function _getPassphrase()
{
if (!isset($this['key'])) {
$passphraseKey = isset($this['passphraseKey'])
? $this['passphraseKey']
: 'passphraseKey';
$this['key'] = \PMVC\plug('get')->get($passphraseKey);
}
if (is_null($this['key'])) {
throw new UnexpectedValueException(
'[SimpleEncryptor] Passphrase is not setted.'
);
}
return $this['key'];
}
private function _isCipher($method)
{
if (empty($this->_methods)) {
$this->_methods = array_flip(openssl_get_cipher_methods());
}
$method = strtolower($method);
if (isset($this->_methods[$method])) {
return true;
} else {
return false;
}
}
private function _genIv($method)
{
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
return $iv;
}
/**
* @see http://micmap.org/php-by-example/en/function/openssl_encrypt
*/
public function encode($string)
{
$passphrase = $this->_getPassphrase();
if ($this->_isCipher($this['method'])) {
if (empty($this['iv'])) {
$this['iv'] = $this->_genIv($this['method']);
}
return openssl_encrypt(
$string,
$this['method'],
$passphrase,
0,
$this['iv']
) .
'|' .
base64_encode($this['iv']);
} else {
return openssl_encrypt($string, $this['method'], $passphrase);
}
}
/**
* @see http://micmap.org/php-by-example/en/function/openssl_decrypt
*/
public function decode($string)
{
$passphrase = $this->_getPassphrase();
$data = explode('|', $string);
if (isset($data[1])) {
return openssl_decrypt(
$data[0],
$this['method'],
$passphrase,
0,
base64_decode($data[1])
);
} else {
return openssl_decrypt($data[0], $this['method'], $passphrase);
}
}
}