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 | <?php
/**
* Mcrypt wrapper class
*
* This class provides encryption capabilities using the mcrypt library and
* also mhash for making adequate-length keys. Each instance of the class
* acts as an encryption object for a particular cipher/mode/key combination.
*
* e.g.
* $enc = new Encrypt('my secret key', MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
* // Will output 'some secret text'
* echo $enc->decrypt($enc->encrypt('some secret text'));
*/
class Encrypt
{
private $module, $iv_size, $key;
public function __construct($key, $cipher = 'rijndael-256', $mode = 'cbc')
{
// Open the module
$this->module = mcrypt_module_open($cipher, '', $mode, '');
if ( $this->module === FALSE )
throw new Exception("Encrypt: Could not load cipher '$cipher' in mode '$mode'");
// Make the correct length key
$this->key = substr(bin2hex(mhash(MHASH_SHA256, $key)), 0, mcrypt_enc_get_key_size($this->module));
// Store the IV size
$this->iv_size = mcrypt_enc_get_iv_size($this->module);
}
public function encrypt($data)
{
$iv = mcrypt_create_iv($this->iv_size, MCRYPT_DEV_URANDOM);
mcrypt_generic_init($this->module, $this->key, $iv);
$retval = $iv . mcrypt_generic($this->module, $data);
mcrypt_generic_deinit($this->module);
return $retval;
}
public function decrypt($data)
{
$iv = substr($data, 0, $this->iv_size);
mcrypt_generic_init($this->module, $this->key, $iv);
$retval = rtrim(mdecrypt_generic($this->module, substr($data, $this->iv_size)), "\0");
mcrypt_generic_deinit($this->module);
return $retval;
}
public function encode($data)
{
return base64_encode($this->encrypt($data));
}
public function decode($data)
{
return $this->decrypt(base64_decode($data));
}
public function encode_var($data)
{
return base64_encode($this->encrypt(serialize($data)));
}
public function decode_var($data)
{
return unserialize($this->decrypt(base64_decode($data)));
}
}
|