The easiest and safest way to create KEY and SECRET APIs in Python

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

I am developing a Django-tastypie based application.

+4
source share
3 answers

EDIT: for a very safe way to generate random numbers, you should use urandom:

from binascii import hexlify

key = hexlify(os.urandom(lenght))

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

You can simply generate the keys of the desired length in the python path:

import random
import string

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

key = generate_key(40).
, , , string.ascii_lowercase , ..

Api tastypie, , https://django-tastypie.readthedocs.org/en/latest/authentication.html#apikeyauthentication

+8

, T. Opletals.

random.choice, . random.SystemRandom(), , linux .

def generate_key(length):
    char_set = string.ascii_letters + string.punctuation                    
    urand = random.SystemRandom()                                           
    return ''.join([urand.choice(char_set) for _ in range(length)])
0

Python 3.6 , secrets - :

The secrets module is used to generate 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 for the default pseudo-random number generator in a random module, which is intended for modeling and modeling, and not for protection or cryptography.

eg. to generate a 16-byte token:

>>> import secrets
>>> secrets.token_urlsafe(16)
'zs9XYCbTPKvux46UJckflw'
>>> secrets.token_hex(16)
'6bef18936ac12a9096e9fe7a8fe1f777'
0
source

Source: https://habr.com/ru/post/1625105/


All Articles