pythondjangotastypie

What is the simplest and safest method to generate an API KEY and SECRET in Python


I need to generate an 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 developing a Django-tastypie framework-based app.


Solution

  • 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