Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Validate and generate Hmailserver passwords using PHP
<?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
You can’t perform that action at this time.