Created
December 8, 2014 13:06
-
-
Save hazarkarabay/286902c29314cd1fc5fc to your computer and use it in GitHub Desktop.
Validate and generate Hmailserver passwords using PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* A poor implementation of Hmailserver's HashCreator.h in PHP | |
* | |
* Blowfish(ETBlowFish) and "plaintext"(ETNone) not currently supported. | |
* | |
* This matches with accountpwencryption field on DB. Hmail_Pass class uses different constants for types, like original source. | |
* From \hmailserver\source\Server\Common\Util\Crypt.h | |
* ETNone = 0, | |
ETBlowFish = 1, | |
ETMD5 = 2, | |
ETSHA256 = 3 | |
* | |
* @author Hazar | |
*/ | |
class Hmail_Pass { | |
// From hmailserver\source\Server\Common\Util\Hashing\HashCreator.h | |
const SALT_LENGTH = 6; | |
const SHA1 = 1; | |
const SHA256 = 2; | |
const MD5 = 3; | |
const hex = 1; | |
const base64 = 2; | |
public function GenerateHash($string, $salt = NULL, $output = self::hex) { | |
if (!$salt || empty($salt) || strlen($salt) != self::SALT_LENGTH) { | |
$salt = substr(md5(rand()), 0, self::SALT_LENGTH); | |
} | |
return $salt . self::GetHash($salt . $string, self::SHA256, $output); | |
} | |
public function ValidateHash($password, $originalHash, $useSalt = true, $hashType = self::SHA256) { | |
if ($useSalt) { | |
$salt = self::GetSalt($originalHash); | |
$hash = self::GetHash($salt . $password, $hashType); | |
return ($originalHash == ($salt . $hash)); | |
} else { | |
$hash = self::GetHash($password, $hashType); | |
return ($originalHash == $hash); | |
} | |
} | |
private function GetSalt($string) { | |
return substr($string, 0, self::SALT_LENGTH); | |
} | |
private function GetHash($string, $encoding = self::SHA256, $output = self::hex) { | |
$raw = ($output == self::base64) ? true : false; | |
switch ($encoding) { | |
case self::SHA1: | |
$hash = hash('sha1', $string, $raw); | |
break; | |
case self::SHA256: | |
$hash = hash('sha256', $string, $raw); | |
break; | |
case self::MD5: | |
$hash = hash('md5', $string, $raw); | |
break; | |
} | |
return ($raw) ? base64_encode($hash) : $hash; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment