add some changes
[Snippets.git] / hash.class.php
CommitLineData
95d2126a 1<?php
a4685b95
S
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>
95d2126a
S
6 */
7class hash {
701c06d4
S
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 = '';
95d2126a
S
31
32 /**
33 * constructor to validate algorithm
34 *
701c06d4
S
35 * @param string $algo
36 * @param string $raw
37 * @param string $hmac
38 * @param string $key
95d2126a 39 */
701c06d4 40 public function __construct ($algo, $raw = '', $hmac = '', $key = '') {
01281009
S
41 $this->raw = $raw;
42 $this->hmac = $hmac;
43 $this->key = $key;
5f6347bf 44
95d2126a 45 if (in_array($algo, hash_algos())) {
01281009 46 $this->algo = $algo;
5f6347bf
S
47 }
48 else {
95d2126a
S
49 die("algorithm ".$algo." not supported");
50 }
51 }
52
53 /**
54 * hash given data with given algorithm
55 *
701c06d4
S
56 * @param string $data
57 * @return string
95d2126a 58 */
01281009
S
59 public function hash ($data) {
60 if (!empty($this->hmac)) {
61 return hash_hmac($this->algo, $data, $this->key, $this->raw);
5f6347bf
S
62 }
63 else {
01281009
S
64 return hash($this->algo, $data, $this->raw);
65 }
95d2126a
S
66 }
67
68 /**
69 * hash given file with given algorithm
70 *
701c06d4
S
71 * @param string $file
72 * @return string
95d2126a 73 */
01281009
S
74 public function hash_file ($file) {
75 if (!empty($this->hmac)) {
76 return hash_hmac_file($this->algo, $file, $this->key, $this->raw);
5f6347bf
S
77 }
78 else {
01281009
S
79 return hash_file($this->algo, $file, $this->raw);
80 }
95d2126a
S
81 }
82
83 /**
84 * compare the given data
85 *
701c06d4
S
86 * @param string $hash
87 * @param string $data
95d2126a
S
88 * @return boolean
89 */
01281009
S
90 public function compare ($hash, $data) {
91 $newhash = $this->hash($data);
5f6347bf 92
95d2126a
S
93 if ($newhash == $hash) {
94 return true;
95 }
5f6347bf 96
95d2126a
S
97 return false;
98 }
99
100 /**
101 * compare the given file
102 *
701c06d4
S
103 * @param string $hash
104 * @param string $file
95d2126a
S
105 * @return boolean
106 */
01281009
S
107 public function compare_file ($hash, $file) {
108 $newhash = $this->hash_file($file);
5f6347bf 109
95d2126a
S
110 if ($newhash == $hash) {
111 return true;
112 }
5f6347bf 113
95d2126a
S
114 return false;
115 }
116}
117?>