用Python生成API KEY和SECRET的最简单,最安全的方法是什么 [英] Whats the simplest and safest method to generate a API KEY and SECRET in Python

查看:858
本文介绍了用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

这篇关于用Python生成API KEY和SECRET的最简单,最安全的方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆