-
Notifications
You must be signed in to change notification settings - Fork 7
/
crypt.php
82 lines (73 loc) · 1.73 KB
/
crypt.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
<?php
if (!defined('FREEPBX_IS_AUTH')) { die('No direct script access allowed'); }
/*
* Allows encrypt and decrypt
*/
class Crypt {
/**
* Gets a random value for encryption
* - From php.net docs
*
* @param $iv_len
* length of random variable
*/
function getRndIV($iv_len) {
$iv = '';
while ($iv_len-- > 0) {
$iv .= chr(mt_rand() & 0xff);
}
return $iv;
}
/**
* Encrypts string
* - From php.net docs
*
* @param $str
* string to encrypt
* @param $salt
* password to use for encryption
* @param $iv_len
* length of random number
*/
function encrypt($str, $salt, $iv_len = 16) {
$str .= "\x13";
$n = strlen($str);
if ($n % 16) $str .= str_repeat("\0", 16 - ($n % 16));
$i = 0;
$enc_text = $this->getRndIV($iv_len);
$iv = substr($salt ^ $enc_text, 0, 512);
while ($i < $n) {
$block = substr($str, $i, 16) ^ pack('H*', md5($iv));
$enc_text .= $block;
$iv = substr($block . $iv, 0, 512) ^ $salt;
$i += 16;
}
return base64_encode($enc_text);
}
/**
* Decrypts string
* - From php.net docs
*
* @param $enc
* encrypted string to decrypt
* @param $salt
* password to use for encryption
* @param $iv_len
* length of random number
*/
function decrypt($enc, $salt, $iv_len = 16) {
$enc = base64_decode($enc);
$n = strlen($enc);
$i = $iv_len;
$str = '';
$iv = substr($salt ^ substr($enc, 0, $iv_len), 0, 512);
while ($i < $n) {
$block = substr($enc, $i, 16);
$str .= $block ^ pack('H*', md5($iv));
$iv = substr($block . $iv, 0, 512) ^ $salt;
$i += 16;
}
return preg_replace('/\\x13\\x00*$/', '', $str);
}
}
?>