1
\$\begingroup\$

I want to make users login into an app. The code on my server serves a "token". This is based on a salt that is saved for each user, the login date, expDate and the userId. That value is hashed by the main key and that result is sent back to the user. If the app needs some data the token and user ID is sent to the server to decrypt it. Is this a solid approach? The server uses SSL.

public $secret = "898appxp132m}]23E";


function generateApiKey($userId){

    //generate the salt, experation date, and login date
    $salt = base64_encode(openssl_random_pseudo_bytes(128, $secure));
    while(!$secure){
        $salt = base64_encode(openssl_random_pseudo_bytes(128, $secure));
    }

    $loginDate = date("Y-m-d");
    $expDate = date("Y-m-d");

    //insert at the database
    $this->load->model("Api_Model");
    $this->Api_Model->insertApiInformation($userId,$salt,$loginDate,$expDate);

    //generate the actual public key
    $userSalt = $salt . hash("sha512", $userId . $loginDate . $expDate . $salt);

    return hash("sha512", $userSalt . $this->secret . $userId);
}

function verifyApiKey($publicHash, $userId){

    //insert at the database
    $this->load->model("Api_Model");
    $info = $this->Api_Model->getApiInformation($userId);

    //generate the actual public key
    $userSalt = $info[0]->user_token . hash("sha512", $userId . $info[0]->date_login . $info[0]->date_expires . $info[0]->user_token);

    if(hash("sha512", $userSalt . $this->secret . $userId) == $publicHash){
        return $this->generateApiKey($userId);
    } else {
        return false;
    }
}

I have changed my code a bit since the token is guessable. I thought that maybe it's better to change the code on each request when the previous code was valid. And I have used SHA512 for a longer token.

\$\endgroup\$
  • \$\begingroup\$ Personally, I'd suggest using an OAuth style approach (without the multiple legs) as AWS does for their API authentication. The long and short of it is that registered users have a public and private key/token, and you each use the private key as the salt to create a hash representation (see: signature) of the data payload. The server recreates the hash and compares it to the one provided to validate the request (lookup private key by the public key provided in the request) \$\endgroup\$ – Robbie Averill Jul 27 '16 at 0:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.