phpasp-classicphash

Generate hash using PHASH with PHP


How can I generate a PHASH value from a string in PHP?

I've inherited an ASP codebase that utilizes PHASH with strings (not paths to images). From research, PHASH is used for images.

I'm currently rewriting this part of the codebase using PHP, and there's a couple of libraries that seem useful:

However, they both require a path to an image. I've tried jenssegers/imagehash and this throws an exception when I pass a random string.

Code below of how PHASH is currently used within the legacy codebase:

sLoginPassword = RequestValue("Password")
SQLVal(PHASH(sLoginPassword))

Update

PHASH is a custom function within the codebase, I failed to find it originally due to mixed casing (PHash vs PHASH).

Luckily I found the following SO answer which is written in C#. Thanks to @Lathejockey81 for provding the answer, I've converted this into PHP below (as an answer).


Solution

  • Custom PHASH function converted from SO answer:

    function PHASH($string)
    {
        $value = trim(strtoupper($string));
    
        $dAccumulator = 0;
        $asciiBytes = [];
    
        for($i = 0; $i < strlen($value); $i++) {
            $asciiBytes[] = ord($value[$i]);
        }
    
        for($i = 0; $i < count($asciiBytes); $i++) {
            if(($i & 1) == 1) {
                $dAccumulator = cos($dAccumulator + (float) $asciiBytes[$i]);
            } else {
                $dAccumulator = sin($dAccumulator + (float) $asciiBytes[$i]);
            }
        }
        $dAccumulator = $dAccumulator * pow(10, 9);
    
        return round($dAccumulator);
    }