Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP API Key Generator

Does anyone know of any API key generator script/class for PHP? The class should have method generate, that would generate a key and isValid() method, to check if the key is valid.

like image 812
xpepermint Avatar asked Sep 19 '09 12:09

xpepermint


People also ask

What is an API key?

An application programming interface (API) key is a code used to identify and authenticate an application or user. API keys are available through platforms, such as a white-labeled internal marketplace. They also act as a unique identifier and provide a secret token for authentication purposes.


1 Answers

There are multiple ways to generate API keys. I've used following 3 methods depending on the applications,

  1. Base62(random). Generate a large secure random number and Base-62 encode it. The key looks like "w5vt2bjzf8ryp63t". This is good for self-provisioned system. You don't have to worry about collision and inappropriate keys. You have to check database to know if the key is valid.

  2. Base62(MD5-HMAC(key, Normalize(referer))). This works great if the API is only allowed from one site. Just check the HMAC of the normalized referer and you know if the key is valid, no database access. You need to keep the HMAC key secret to do this.

  3. Human assigned friendly names like "example.com". This works great if API users are required to own a domain or they are your corporate partners.

Please keep in mind that there is no security in API keys. It's just a name assigned to your API application. More and more people are using terms like "App ID" or "Dev ID" to reflect what it really is. You have to assign another secret key if you want secure your protocol, like consumer_key/consumer_secret in OAuth.

like image 186
ZZ Coder Avatar answered Oct 15 '22 20:10

ZZ Coder