Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the simplest and safest method to generate a API KEY and SECRET in Python

I need to generate a API key and Secret that would be stored in a Redis server. What would be the best way to generate a key and secret?

I am develop a Django-tastypie framework based app.

like image 459
Dhanushka Amarakoon Avatar asked Jan 20 '16 10:01

Dhanushka Amarakoon


People also ask

Which is the most secure method to transfer an API key?

There is only one reliable way: use HTTPs for your web site to allow the users to retrieve the key. Then during the API calls HTTPS is no longer required. Your users can use HMAC authentication to hash the key with a shared secret.

How do I get my API key and secret key?

To obtain a new API Key and API Secret, log in to your SendSafely account and go to the Edit Profile page. From there you should see an API Access Keys section that allows you to manage your API Keys.


2 Answers

If you're on Python 3.6 or later, the secrets module is the way to go:

The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.

In particular, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.

e.g. to generate a 16 byte token:

>>> import secrets >>> secrets.token_urlsafe(16) 'zs9XYCbTPKvux46UJckflw' >>> secrets.token_hex(16) '6bef18936ac12a9096e9fe7a8fe1f777' 
like image 181
Moby Duck Avatar answered Sep 23 '22 02:09

Moby Duck


For python3.6+

import secrets  generated_key = secrets.token_urlsafe(length) 

For older versions of python:

for a very secure way of generating random number, you should use urandom:

from binascii import hexlify  key = hexlify(os.urandom(length)) 

this will produce bytes, call key.decode() if you need a string

For general non-secure random strings, with more settings, you can just generate keys of your desired length the python way:

import random import string  def generate_key(length):     return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length)) 

And then you can just call it with your desired length key = generate_key(40).
You can specify what alphabet you want to use, for example using only string.ascii_lowercase for key consisting of only lowercase letters etc.

There is also Model for Api authentication in tastypie, might be worth checking out https://django-tastypie.readthedocs.org/en/latest/authentication.html#apikeyauthentication

like image 40
T. Opletal Avatar answered Sep 23 '22 02:09

T. Opletal