Search code examples
phphashmcrypts2kmhash

Alternative to mhash_keygen_s2k()


The mcrypt_encrypt manual page says that:

It is recommended to use the mhash functions to create a key from a string.

But the introduction of the mhash manual says that:

Note: This extension is obsoleted by Hash.

However, the closest thing I could find to the rather useful mhash_keygen_s2k() function was the hash_pbkdf2() function. However, I'm not even sure if it fits the job since it only exists in the SVN.

So, can I rely on the mhash extension, or it will eventually become deprecated and dropped? If so, is there any alternative built-in function or do I have to implement the Salted S2K algorithm myself?


Solution

  • I ended up peeking into mhash source code porting this to PHP:

    function keygen_s2k($hash, $password, $salt, $bytes)
    {
        $result = false;
    
        if (extension_loaded('hash') === true)
        {
            foreach (range(0, ceil($bytes / strlen(hash($hash, null, true))) - 1) as $i)
            {
                $result .= hash($hash, str_repeat("\0", $i) . str_pad(substr($salt, 0, 8), 8, "\0", STR_PAD_RIGHT) . $password, true);
            }
    
            $result = substr($result, 0, intval($bytes));
        }
    
        return $result;
    }
    

    If anyone knows any alternative built-in function, I would still like to hear about it.