PHP API Key Generator

2019-01-12 22:33发布

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.

9条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-12 23:09

GUID would work but is not cryptographically secure.

Server answers use md5 or sha1 hashing methods on microtime() or mt_rand.

Hashing a uniqid, uuid or timestamp would not necessarily create unique results! Actually hashing increases the chance of collisions so I would strongly advise against this.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-12 23:13

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.

查看更多
看我几分像从前
4楼-- · 2019-01-12 23:15

Well as it has been mentioned, it is all dependant on the situation. One method that I needed to use was to authenticate a referer url with a specifically assigned API key. So with the API key all that was really needed was (pseudo) key = md5(referer url + name + salt) which you then can have a checksum for. I know it has been mentioned similar to this before, but it is just that way. As for the isValid() function, all you need to do with this is compare it against the checksum and URL.

Edit: Just realised the age of the original question :S

查看更多
对你真心纯属浪费
5楼-- · 2019-01-12 23:20

Here is my simple answer to this question:

$key = implode('-', str_split(substr(strtolower(md5(microtime().rand(1000, 9999))), 0, 30), 6));
查看更多
啃猪蹄的小仙女
6楼-- · 2019-01-12 23:22

just use something like this (pseudo code) sha1(salt + time + mac-addr + another salt + some other random data) crc32 or md5 would also work inestead of sha1 and store it in a database and then isValid() checks the db if the key exists?

查看更多
地球回转人心会变
7楼-- · 2019-01-12 23:23

See uniqid:

string uniqid ([ string $prefix = "" [, bool $more_entropy = false ]] )
查看更多
登录 后发表回答