<?php
class Hash {
public static function prepare_password($password) {
// salt
$salt = self::create("sha256", time(), rand());
// hash (includes the salt)
$hash = self::create("sha256", $password, $salt);
return array('salt' => $salt, 'hash' => $hash);
}
public static function encrypt_password($password, $salt) {
$hash = self::create("sha256", $password, $salt);
return $hash;
}
/**
*
* @param string $algo => sha256, sha1, md5, whirlpool
* @param string $data => The data that needs to be hashed
* @param string $salt => if you want to use a salt to make it more secure (optional)
* @return Hashed data
* @throws Exception => if an error is encoutered an exception will be thrown
*/
static public function create($algo, $data, $salt = Null) {
if ($algo && $data) {
if($salt != Null && is_string($salt)){
$context = hash_init($algo, HASH_HMAC, $salt);
} else {
$context = hash_init($algo);
}
if(!$context) {
throw new Exception("Error salting data");
}
hash_update($context, $data);
return hash_final($context);
} else {
throw new Exception("Creating hash failed");
}
}
/**
* token will provid a string or md5 string of a unique id
*
* @param string $salt => if you want to use a salt to make it more secure (optional)
* @return string => unique id or if salt provided a salted version
*/
static public function token($salt = NULL){
$data = uniqid(microtime());
if($salt != Null && is_string($salt))
return self::create ("sha256", $data, $salt);
else
return $data;
}
}