我需要生成将存储在Redis服务器中的API密钥和密钥.生成密钥和密码的最佳方式是什么?
我正在开发一个基于Django-Tatypie框架的应用程序.
我需要生成将存储在Redis服务器中的API密钥和密钥.生成密钥和密码的最佳方式是什么?
我正在开发一个基于Django-Tatypie框架的应用程序.
python3.6+美元
import secrets
generated_key = secrets.token_urlsafe(length)
older versions of python美元:
为了获得生成随机数的非常安全的方法,您应该使用Uradom:
from binascii import hexlify
key = hexlify(os.urandom(length))
这将生成字节,如果需要字符串,请拨打key.decode()
对于general non-secure random strings,如果设置更多,您只需通过python方式生成所需长度的密钥即可:
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.
Tatypie中也有用于Api身份验证的模型,可能值得一查https://django-tastypie.readthedocs.org/en/latest/authentication.html#apikeyauthentication