0

In my django settings.py file there is:

SECRET_KEY = '1qpps_5yf@e_++wwicusr*8#lm)^m=rjhgk#&qq1w*p*2d3c4z'

I need some function to convert this string (well it can be any string, lets assume it's not empty) to shorter/longer string. I mean I need key but for example with length=16. Well If SECRET_KEY is longer than 16 it's easy to just substring it, but if its shorter then I don't want to "pad" missing values with some constatnt char.

So I need function which takes string with length > 0 and generates key with length = 16. Even more simply: I need key generator which will generate 16 characters string based on some seed (seed = SECRET_KEY)

edit --------------------

found good solution here: Efficiently generate a 16-character, alphanumeric string

import random
random.seed(settings.SECRET_KEY)
key = ''.join(random.choice('1234567890qwertyuiopasdfghjklzxcvbnm,./;@[]!#$%^&*()_+=-') for i in range(16))

I hope random.seed(settings.SECRET_KEY) is not big security whole in django app :P

4

1 回答 1

2

您可以散列任何值,并从中获取 16 个字节:

>>> import hashlib
>>> hashlib.md5("123").digest()
' ,\xb9b\xacY\x07[\x96K\x07\x15-#Kp'

您还没有说字符串中可以接受哪些字符,这将为您提供任意字节值。

于 2012-12-15T17:27:15.677 回答