用Python生成API KEY和SECRET的最简单,最安全的方法是什么
我需要生成一个API密钥和Secret密钥,并将其存储在Redis服务器中。
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?
我正在开发一个基于Django-tastypie框架的应用程序。
I am develop a Django-tastypie framework based app.
对于 python3.6 +
import secrets
generated_key = secrets.token_urlsafe(length)
对于 Python的较旧版本:
要非常安全地生成随机数,应使用urandom:
for a very secure way of generating random number, you should use urandom:
from binascii import hexlify
key = hexlify(os.urandom(length))
这将产生字节,如果需要字符串,请调用 key.decode()
this will produce bytes, call key.decode()
if you need a string
对于常规非安全随机字符串 ,使用更多设置,您可以通过python方式生成所需长度的键:
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))
然后您可以用所需的长度调用它 key = generate_key(40)
。
您可以指定要使用的字母,例如仅使用 string.ascii_lowercase
来构成以下字母:仅小写字母等。
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.
好吃的饼中也有用于Api验证的模型,可能值得一试 https://django-tastypie.readthedocs.org/en/latest/authentication.html#apikeyauthentication
There is also Model for Api authentication in tastypie, might be worth checking out https://django-tastypie.readthedocs.org/en/latest/authentication.html#apikeyauthentication