add ldap class
[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 {
01281009
S
8 protected $raw;
9 protected $hmac;
10 protected $key;
95d2126a
S
11 protected $algo;
12
13 /**
14 * constructor to validate algorithm
15 *
01281009
S
16 * @param string $algo
17 * @param optional $raw
18 * @param optional $hmac
19 * @param optional $key
95d2126a 20 */
01281009
S
21 public function __construct ($algo, $raw = Null, $hmac = Null, $key = Null) {
22 $this->raw = $raw;
23 $this->hmac = $hmac;
24 $this->key = $key;
95d2126a 25 if (in_array($algo, hash_algos())) {
01281009 26 $this->algo = $algo;
95d2126a
S
27 } else {
28 die("algorithm ".$algo." not supported");
29 }
30 }
31
32 /**
33 * hash given data with given algorithm
34 *
35 * @param mixed $data
95d2126a
S
36 * @return hash
37 */
01281009
S
38 public function hash ($data) {
39 if (!empty($this->hmac)) {
40 return hash_hmac($this->algo, $data, $this->key, $this->raw);
41 } else {
42 return hash($this->algo, $data, $this->raw);
43 }
95d2126a
S
44 }
45
46 /**
47 * hash given file with given algorithm
48 *
49 * @param mixed $file
95d2126a
S
50 * @return hash
51 */
01281009
S
52 public function hash_file ($file) {
53 if (!empty($this->hmac)) {
54 return hash_hmac_file($this->algo, $file, $this->key, $this->raw);
55 } else {
56 return hash_file($this->algo, $file, $this->raw);
57 }
95d2126a
S
58 }
59
60 /**
61 * compare the given data
62 *
63 * @param hash $hash
64 * @param mixed $data
95d2126a
S
65 * @return boolean
66 */
01281009
S
67 public function compare ($hash, $data) {
68 $newhash = $this->hash($data);
95d2126a
S
69 if ($newhash == $hash) {
70 return true;
71 }
72 return false;
73 }
74
75 /**
76 * compare the given file
77 *
78 * @param hash $hash
79 * @param mixed $file
95d2126a
S
80 * @return boolean
81 */
01281009
S
82 public function compare_file ($hash, $file) {
83 $newhash = $this->hash_file($file);
95d2126a
S
84 if ($newhash == $hash) {
85 return true;
86 }
87 return false;
88 }
89}
90?>