0

I'm using PHP V5.6.16

I'm having this error while trying to create an access token

crypt(): No salt parameter was specified. You must use a randomly generated salt and a strong hash function to produce a secure hash

This is the function I'm using.

    /**
     * Generate a token
     * @return string token
     */
   private function getToken()
    {
    $random_id_length = 15;

 //generate a random id encrypt it and store it in $rnd_id
    $rnd_id = crypt(uniqid(rand(), CRYPT_EXT_DES));

    //to remove any slashes that might have come
    $rnd_id = strip_tags(stripslashes($rnd_id));

    //Removing any . or / and reversing the string
    $rnd_id = str_replace(".", "", $rnd_id);
    $rnd_id = strrev(str_replace("/", "", $rnd_id));

    //finally I take the first 10 characters from the $rnd_id
    $rnd_id = substr($rnd_id, 0, $random_id_length);

    return urldecode($rnd_id);
}

How to fix it?

Scott Arciszewski
  • 33,610
  • 16
  • 89
  • 206
Aviv Paz
  • 1,051
  • 3
  • 13
  • 28
  • 3
    I'd recommend using [`password_hash`](http://php.net/manual/en/function.password-hash.php). – Joachim Isaksson Feb 11 '16 at 08:49
  • 1
    try running an `if (CRYPT_EXT_DES == 1) echo "supported"` to see if you have support for `CRYPT_EXT_DES` – Oliver Nybroe Feb 11 '16 at 08:55
  • Is there an specific reason to why you would wan't to create your own salt and not use the `password_hash` method as the `password_has`method is a lot more straight forward. – Oliver Nybroe Feb 11 '16 at 09:01
  • 3
    *"The salt parameter is optional. However, crypt() creates a weak password without the salt. PHP 5.6 or later raise an E_NOTICE error without it. Make sure to specify a strong enough salt for better security."* – http://php.net/crypt – deceze Feb 12 '16 at 16:16
  • 2
    You're really just throwing together a bunch of random functions here, most of which you're misusing. What's the purpose of this code? Generating a random string? There are better and more random ways to do that... – deceze Feb 12 '16 at 16:17

1 Answers1

3

I'm having this error while trying to create an access token

Don't use crypt(). Grab a copy of paragonie/random_compat and use random_bytes() instead.

function getToken($randomIdLength = 10)
{
    $token = '';
    do {
        $bytes = random_bytes($randomIdLength);
        $token .= str_replace(
            ['.','/','='], 
            '',
            base64_encode($bytes)
        );
    } while (strlen($token) < $randomIdLength);
    return $token;
}
Scott Arciszewski
  • 33,610
  • 16
  • 89
  • 206