add some changes
[Snippets.git] / hash.class.php
1 <?php
2 /**
3 * @author Jan Altensen (Stricted)
4 * @copyright 2013-2014 Jan Altensen (Stricted)
5 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
6 */
7 class hash {
8 /**
9 * raw output
10 * @var string
11 */
12 protected $raw = '';
13
14 /**
15 * hash with hmac
16 * @var string
17 */
18 protected $hmac = '';
19
20 /**
21 * hmac key
22 * @var string
23 */
24 protected $key = '';
25
26 /**
27 * hash algorithm
28 * @var string
29 */
30 protected $algo = '';
31
32 /**
33 * constructor to validate algorithm
34 *
35 * @param string $algo
36 * @param string $raw
37 * @param string $hmac
38 * @param string $key
39 */
40 public function __construct ($algo, $raw = '', $hmac = '', $key = '') {
41 $this->raw = $raw;
42 $this->hmac = $hmac;
43 $this->key = $key;
44
45 if (in_array($algo, hash_algos())) {
46 $this->algo = $algo;
47 }
48 else {
49 die("algorithm ".$algo." not supported");
50 }
51 }
52
53 /**
54 * hash given data with given algorithm
55 *
56 * @param string $data
57 * @return string
58 */
59 public function hash ($data) {
60 if (!empty($this->hmac)) {
61 return hash_hmac($this->algo, $data, $this->key, $this->raw);
62 }
63 else {
64 return hash($this->algo, $data, $this->raw);
65 }
66 }
67
68 /**
69 * hash given file with given algorithm
70 *
71 * @param string $file
72 * @return string
73 */
74 public function hash_file ($file) {
75 if (!empty($this->hmac)) {
76 return hash_hmac_file($this->algo, $file, $this->key, $this->raw);
77 }
78 else {
79 return hash_file($this->algo, $file, $this->raw);
80 }
81 }
82
83 /**
84 * compare the given data
85 *
86 * @param string $hash
87 * @param string $data
88 * @return boolean
89 */
90 public function compare ($hash, $data) {
91 $newhash = $this->hash($data);
92
93 if ($newhash == $hash) {
94 return true;
95 }
96
97 return false;
98 }
99
100 /**
101 * compare the given file
102 *
103 * @param string $hash
104 * @param string $file
105 * @return boolean
106 */
107 public function compare_file ($hash, $file) {
108 $newhash = $this->hash_file($file);
109
110 if ($newhash == $hash) {
111 return true;
112 }
113
114 return false;
115 }
116 }
117 ?>