Storing API keys on the server

I have a service in which users have an API key. I need to save the keys so that they can be used to validate API requests.

If I store the keys in clear text in my database, I worry about someone accessing the db, grabbing all the keys of the plaintext api, and then using them to personify others (most likely there will be big problems if anyone got access to db though).

This is similar to storing user passwords, where you simply store the hash and check with this - however, most APIs allow you to view your API keys, which means that you need to save them in some way that can be recovered.

Is there any best practice for this?

thanks

+7
security api
source share
1 answer

The threat of someone getting the database and getting the keys means that they can use the api keys to access the data in the database that they already have, so there is no win.

The threat that someone can access the database, get passwords, means that they can reuse these passwords on other websites with the same username, because people tend to reuse their passwords.

Another reason is that passwords in an explicit or easily changing way are someone from your company who can take hold of passwords and start doing bad things by acting as a user. What risk can you have if your API keys are clear.

Typically, an HMAC is a solution for cryptographically calculating a secure value from one secret key and some public value.

Look at the HMAC. Using the HMAC, you can load the secret key into memory using the application (configuration file, read AMAZON KMS, enter at the beginning of the application, or, nevertheless, you want to get the secret key there).

Save the token in the database. Token = UUID() e.g. The token must be unique to the user, the token can be a version in case you need to regenerate, and the token can be random (for example, UUID). Token is not a secret.

The API key is calculated using the private key ( SK ) and user token ( UT ) as follows:

 API_SECRET = HMAC(SK, UT) 

Then allocate API_KEY and API_SECRET for the user, and when the user tries to connect, you will calculate API_SECRET :

  • Retrieve a user record from the database (you probably already ask the user to provide their username)
  • Compute API_SECRET from UT in the database:

    API_SECRET_DB = HMAC (SK, UT)

  • Compare the computed API_SECRET_DB with the one specified in the request:

    if (API_SECRET_DB == API_SECRET_FROM_REQUEST) {// user login}

On the bottom line, you protect only the private key, not all credentials.

+4
source share

All Articles