37

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.

fasouto
  • 3,877
  • 2
  • 25
  • 60
Dhanushka Amarakoon
  • 2,704
  • 5
  • 23
  • 39
  • 2
    There's `get_random_string` in `django.utils.crypto`, see http://stackoverflow.com/questions/25943850/django-package-to-generate-random-alphanumeric-string – Kos Mar 27 '17 at 15:37

5 Answers5

58

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'
Community
  • 1
  • 1
Moby Duck
  • 1,015
  • 1
  • 12
  • 13
  • 8
    Thanks! Here's a version to invoke straight from the terminal: `python -c 'import secrets; print(secrets.token_urlsafe(16))'` – Paweł Mucha Mar 31 '19 at 18:10
  • For Windows users running Pawel's code via cmd, if you get the error `SyntaxError: EOL while scanning string literal`, replace the single quotes with double quotes – jarrettyeo May 24 '20 at 03:09
50

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

T. Opletal
  • 1,586
  • 1
  • 13
  • 21
3

you can also use following module to generate random string

 1 - os.urandom(64).encode('hex') #from os module
 2 - uuid.uuid4()                 # from uuid module
 3 - get_random_string(length=32) #from django.utils.crypto
 4 - secrets.token_hex(64)         #from secrets >= python 3.6 
Saurabh Chandra Patel
  • 9,983
  • 3
  • 77
  • 72
0

Adding answer as I can't comment on T. Opletals answer.

You should not use random.choice as random isn't cryptographically secure. A better option would be random.SystemRandom() which uses the system source of randomness, on linux this would be urandom.

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

If you want an easy-to-use but highly customisable key generator, use key-generator pypi package.

Here is the GitHub repo where you can find the complete documentation.

Here's an example:

from key_generator.key_generator import generate

custom_key = generate(2, ['-', ':'], 3, 10, type_of_value = 'char', capital = 'mix', seed = 17).get_key()
print(custom_key)  # ZLFdHXIUe-ekwJCu

Hope this helps :)

Disclaimer: This uses the key-generator library which I made.

Sahith Kurapati
  • 1,091
  • 4
  • 11