Creating API tokens in PHP

noras noras |

Tags: #Authentication #PHP #Web security

In this post I explore the creating of API tokens using PHP in a secure way.

Create the token

 public static function newToken($platform,$secret_key,$type){
	//generating an IV
	$salt  = bin2hex(openssl_random_pseudo_bytes(64));
	$secret_iv = substr(hash('sha256', $salt), 0, 16);
	$secret_key = hash('sha256', $secret_key);
	$encrypt_method = "AES-256-CBC";
	$token = openssl_encrypt($platform.$salt, $encrypt_method, $secret_key, 0, $secret_iv);
	// store in db ($platform,$salt,$secret_iv ,$secret_key,$token)

	//  when inserting get the new token id ===>  $id 
	$token = base64_encode($token_id.'-'.$platform.'-'.$token);
	return $token;

Verify the token

 public static function verifyToken($token_in){
	$encrypt_method = "AES-256-CBC";

	try {
		$pieces = explode("-", $token_in);

		if(!isset($pieces[1]) || !isset($pieces[2]))
			return false;


		// getTokenById($id)  ==> should return ==> $platform,$salt,$secret_iv ,$secret_key,$token

		//check if it acctually returns somthing otherwise return false
			return false;
		//get the platform,salt , and keys 

		$decrypted_token = openssl_decrypt($token_in, $encrypt_method, $secret_key, 0, $secret_iv);
			return true;
	} catch (Exception $e) {
		return false;
	return false;

About the author


"Senior Software Engineer. MSc in Computer systems and Networks with big interest in security. Loves to play with Android code and does security research for fun and profit. Speaks 4 languages and codes in much more."

Related articles

Tags: #Authentication #PHP #Web security

Copyright © 2020 - nindoda.com